+ 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?
7 Respuestas
+ 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.
+ 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;
+ 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
+ 1
@Hassie you take my answers away😊😂
+ 1
wait, even if the statements are false it will output the other statements?
+ 1
@Jonas awe 😀
+ 1
that's the best answer i've ever heard in my life