+ 1

Switch statement in java

I bumped into a question just now about a switch statement: int a = 2; int x = 0; switch(a){ case 1: ++x; case 2: ++x; case 3: ++x; default: ++x; } System.out.print(x); //output = 3 I understand that x in this case is being pre incremented but why isnt the code done after the case 2 is exicuted?

9th Apr 2018, 2:36 PM
Evan Martine
3 Réponses
+ 9
There aren't any break statements for any of the cases so they will fall through to the next case until one is reached or the switch statement ends.
9th Apr 2018, 2:38 PM
ChaoticDawg
ChaoticDawg - avatar
+ 19
If break is not used after the case value in switch statement... all the case values will be executed after the given case value in switch parameter edit : chaotic beat me 😉😉😉
9th Apr 2018, 2:39 PM
🌛DT🌜
🌛DT🌜 - avatar
+ 2
ChaoticDawg I figured something was up when var a didnt change and the output was greater than 1
9th Apr 2018, 2:39 PM
Evan Martine