+ 5
Why the result is 17, in this code?
// why the result is 17? public class Program { public static void main(String[] args) { int x = 3; switch(x) { case 1 : {x += x;} case 3 : {x += x;} case 5 : {x += x;} default : {x += 5;} } System.out.print(x); } }
10 odpowiedzi
+ 5
3+3=6
6+6=12
12+5=17
+ 3
*AsterisK*
I have seen this, but I do not understand why SWITCH does not work!
+ 3
VV. because break was not use
+ 3
There is no break statement there. So it continues to the end.
+ 3
https://www.w3schools.com/java/java_switch.asp
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed. !!!!!! (only if there is a match).
The break Keyword
When Java reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need for more testing.
A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch block.
The default Keyword
The default keyword specifies some code to run if there is no case match.
So in may opinion, we have to have 11
3 += 3 --> 6 (case 3)
6 += 5 --> 11 (default).
+ 3
D'Lite
"The reason is because you forgot to add "break; " at the end of the "cases" ..."
So it seems to be, but I have not found somewhere that once a condition is fulfilled all the following are executed, except the default ones.
THANK YOU!
+ 3
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Another point of interest is the break statement. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
+ 2
The reason is because you forgot to add "break; " at the end of the "cases".
When you ran the code, it skipped the "case 1", because x was not 1.
When it got to "case 3", it applied "x += x", thus making x = 6;
The catch is that you wrote
" case 3:{
x += x;
}
"
instead, you should have written
"case 3:{
x += x;
break;
}
"
Because of the the "break" omission, all other blocks of code after "case 1" executed.
Thus this was the flow
case 3 => 3+3 // x = 6
case 5 => 6+6 // x =12
default => x += 5 // x =17
+ 2
Break is missing .