public class Hello {
public static void main(int a) {
switch (a) {
case 1:
System.out.println("Hi");
}
switch (a) {
case 2:
System.out.println("Hello");
}
}
}
Hi, I want to know if it is possible for me to use Switch Case for the same variable twice, like I've done in the snippet attached. Thanks.
The code you have provided works. So long as the variable a
is in scope, you can use it for as many switch
statements as you like.
If you want to check for multiple values of a
in the same switch
, then you should use different cases. E.g.:
switch (a) {
case 1:
System.out.println("a was 1");
break; // if we did not break, then execution would "fall-through" to the next case
case 2:
System.out.println("a was 2");
break;
default:
System.out.println("a was not 1 or 2");
}
Find out more about the switch statement in the Java Documentation.