+ 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; } } }
10 Antworten
+ 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.
+ 3
because after case1 is not break
+ 2
Aahhhh if I don't put break; between the switch cases so all the cases will be executed
Big thinks for your help👍👍
+ 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;
+ 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
+ 1
Yes but the value of x is changed from 2 to 1!!
+ 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
+ 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 );
}}
+ 1
Thanks for your clarification 😊