How does the Java compiler handle the following switch block ? What is the scope of the \'b\' variable ?
Note that the \'b\' variable is declared only in the first b
You can define the scope using {} around your case.
int a = 3;
switch( a ) {
case 0: {
int b = 1;
System.out.println("case 0: b = " + b);
break;
}
case 1: {
// the following line does not compile: b may not have been initialized
// System.out.println("case 1 before: b = " + b);
int b = 2;
System.out.println("case 1 after: b = " + b);
break;
}
default: {
int b = 7;
System.out.println("default: b = " + b);
}
}