Is case java switch statement executing multiple cases for negative int values?

I just run something weird in my java code:

switch (result) { case 0: result_amount = 500; case 1: result_amount = 600; case -1: result_amount = 700; } 

result - from the primitive type int. For values 1 case 1 and case -1 are executed.

Is this the usual behavior in case of switching? If yes: why?

+5
source share
6 answers

You need to use the break keyword after the case block:

 switch (result) { case 0: result_amount = all_amounts[i]; break; case 1: result_amount = all_amounts[i]; break; case -1: result_amount = all_amounts[i+1]; } 

The switch will jump to the correct case tag, and then execute all of the following code, ignoring potential other case tags. You can consider the switch just like a goto .

+8
source

A fall.

citation from the documentation

Break statements are necessary because without them instructions are executed in the switch blocks: all instructions after the match label are executed in sequence, regardless of the expression of subsequent case labels, until the break statement is encountered.

You must add break after each case.

  case 1: result_amount = 600; break; 
+3
source

Without the break statement, the following cases will occur.

0
source
  • In general, the label should be integer / persistent
  • Negative numbers without a decimal point are also considered Integer
  • Thus, there is no need to have Case shortcuts greater than zero

This is a fall through condition.

  switch (result) { case 0: result_amount = all_amounts[i]; case 1: result_amount = all_amounts[i]; case -1: result_amount = all_amounts[i+1]; } 

To avoid this, you should put a break statement

  switch (result) { case 0: result_amount = all_amounts[i]; break; case 1: result_amount = all_amounts[i]; break; case -1: result_amount = all_amounts[i+1]; break; } 

Now only the corresponding case will be executed.

0
source

Remember

This is a mistake that almost every newcomer will make. That's why I like C # more. This does not allow to “fail”.

What you did wrong is that you failed the switch statement. Try using the value 0 as the value of result . It will go through all cases. When the switch queue completes, the following case is true. Therefore, we need to add a break; statement break; for each case of the switch statement.

 switch (result) { case 0: result_amount = 500; break; case 1: result_amount = 600; break; case -1: result_amount = 700; break; } 

But sometimes we want to fail. For example, when we want to calculate the number of days per month:

 switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: days = 31; break; case 2: days = 28; case 4: case 6: //Lots of code... } 
0
source

You must enable break and default for the program to work properly. Let me give you an example.

 switch (result) { case 0: result_amount = 500; break; case 1: result_amount = 600; break; case -1: result_amount = 700; break; } 
0
source

All Articles