Explain me this. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Explain me this.

int x = 0; switch(x) { case 1: System.out.print(1); case 0: System.out.print(1); case 2: System.out.print(3); } Why does this code output 13 instead of 1?

25th Jul 2017, 2:46 PM
Mark Daniel Walker
Mark Daniel Walker - avatar
7 Answers
+ 1
Essentially what is happening is a fall through. Not using breaks is a method of having multiple cases run one block / multiple blocks of code. As soon as one condition is met, it will execute all blocks below that case if there are no breaks or until it reaches a break.
25th Jul 2017, 2:58 PM
Hassie
Hassie - avatar
+ 3
Because you have not added a break statement at the end of each case. So it will go through every statement and output the result of the final statement. fix: case... statements... break; case... Statements... break;
25th Jul 2017, 2:53 PM
Hassie
Hassie - avatar
+ 2
@Mark No, if it's false, it won't be executed.So: int a = 3; switch (a){ case 2: System.out.println(2); case 3: System.out.println(3); case 4: System.out.println(4); } //34
25th Jul 2017, 2:58 PM
Jonas Schröter
Jonas Schröter - avatar
+ 1
@Hassie you take my answers away😊😂
25th Jul 2017, 2:53 PM
Jonas Schröter
Jonas Schröter - avatar
+ 1
wait, even if the statements are false it will output the other statements?
25th Jul 2017, 2:55 PM
Mark Daniel Walker
Mark Daniel Walker - avatar
+ 1
@Jonas awe 😀
25th Jul 2017, 2:55 PM
Hassie
Hassie - avatar
+ 1
that's the best answer i've ever heard in my life
25th Jul 2017, 4:23 PM
Mark Daniel Walker
Mark Daniel Walker - avatar