+ 1
Why it optputs 4??I dont understand..
4 odpowiedzi
+ 3
What does switch statement do?
It starts executing statement blocks when a matching case value is found. It'll keep executing all below statements upto default statement.
Ex.
x=1;
switch(2)
{
case 1:
Block 1
case 2:
Block 2;
..
...
...
case n:
Black n;
default :
Default block;
}
Here all blocks from 2 to Default will be executed !
Once match is found execution starts.
Generally each case block is separated by break; so when break is encountered control reaches out of switch.
Your code has x=1:
switch(x){
case 1 : x++; //match ->x++ ->2
case 2 : x++; //continued ->3
default : x++; //continued -> 4
}
Results is 4.
+ 2
This switch don't have break operation. So, when choose case 1 he also choose case 2 and also choose case default.
+ 2
You dont have any breaks, so the code is executing each case in the switch before being told to jump out. Try this
public class Program
{
public static void main(String[] args) {
int x=1;
switch(x){
case 1 : x++;
break;
case 2 : x++;
break;
default : x++;
}
System.out.print(x);
}
}
0
This code might light something up:
https://code.sololearn.com/cxf0d0Jyi3B8/?ref=app