Case 1
int a = 2;
switch(a){
case 2:
int x = 4;
// executes
case 3:
x = 5;
// executes
case 4:
x = 7;
// executes
}
in this value of x will be 7 because the switch won't break
if it find a matching case.
Case 2
If you want to stop execution on 2 do the following
int a = 2;
switch(a){
case 2:
int x = 4; // variable declaration works even if case wont match. Validity inside switch for every line of code after this line
break;
// executes and break
case 3:
x = 5;
break;
// executes and break
case 4:
x = 7;
break;
// executes and break
default:
// write default case here
}
You need not use int
in every x because of the scope of the declaration throughout the scope.
The scope of the declaration of a variable in the switch will affect the following statements or line of code in the switch. It's because, if the variable declaration it will if the scope is not defined by braces.
Case 3
int a = 3;
switch(a){
case 2:
{
int x = 4;
break; // u can skip this break to. Then also it will throw error.
// x is local variable inside this braces
}
// executes
case 3:
x = 5;
// error
case 4:
x = 7;
// error
System.out.println(""+x);
}
In the above case, it will through the error. Because its scope is only in that case.
In this scenario, the scope of a variable is declared inside the braces. so outside that braces, x won't work. Because x is a local variable in that case condition.