1st Sep 2019, 2:12 PM
Sanzid Sadman
Sanzid Sadman - avatar
4 Respuestas
+ 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.
1st Sep 2019, 2:25 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 2
This switch don't have break operation. So, when choose case 1 he also choose case 2 and also choose case default.
1st Sep 2019, 2:18 PM
id001x
id001x - avatar
+ 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); } }
1st Sep 2019, 2:20 PM
Foobatboy
Foobatboy - avatar
0
This code might light something up: https://code.sololearn.com/cxf0d0Jyi3B8/?ref=app
1st Sep 2019, 2:25 PM
Seb TheS
Seb TheS - avatar