+ 2

Why as output I had 1 ab and not 1 a?

public class Security { int x = 2; public static void main(String[] args) { int x = 1; System.out.println(x); switch(x){ case 1: System.out.print('a'); case 2: System.out.print('b'); break; } } }

28th Dec 2019, 2:02 PM
Hichem GOUIA
Hichem GOUIA - avatar
10 Respostas
+ 3
Hichem GOUIA for x=1 you get "ab" because case 1 is first executed and there is no "break" after printing 'a'. So the control moves to case 2 and prints 'b'. This is generally called "fall through". But if you make x=2 then directly case 2 is executed and prints 'b'. The value passed in switch and the case inside switch has to match.
28th Dec 2019, 2:22 PM
Avinesh
Avinesh - avatar
+ 3
because after case1 is not break
28th Dec 2019, 2:11 PM
zemiak
+ 2
Aahhhh if I don't put break; between the switch cases so all the cases will be executed Big thinks for your help👍👍
28th Dec 2019, 2:38 PM
Hichem GOUIA
Hichem GOUIA - avatar
+ 2
without breaks, it will execute only all cases after true case case 0: System.out.print('@'); //false, not executed case 1: System.out.print('a'); //true, first executed case 2: System.out.print('b'); //second executed break;
28th Dec 2019, 3:02 PM
zemiak
+ 1
And if switch the first declaration int x= 1 and the second to int x = 2 I obtain as output 2 b Instead of 2 ab
28th Dec 2019, 2:04 PM
Hichem GOUIA
Hichem GOUIA - avatar
+ 1
Yes but the value of x is changed from 2 to 1!!
28th Dec 2019, 2:15 PM
Hichem GOUIA
Hichem GOUIA - avatar
+ 1
In the second declaration is x = 2 then the case 1 is not true. It don't print "a" and goes to case 2
28th Dec 2019, 2:23 PM
Julio Codesal
Julio Codesal - avatar
+ 1
int x declared as local variable in main() is not the same as x declared as Security class property try this public class Security { static int x = 2; public static void main(String[] args) { int x = 1; System.out.println( Security.x ); System.out.println( x ); }}
28th Dec 2019, 2:28 PM
zemiak
+ 1
Thanks for your clarification 😊
28th Dec 2019, 3:18 PM
Hichem GOUIA
Hichem GOUIA - avatar