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 branch of the switch statement. Attempting to declare it in the second branch as well results in a "duplicate local variable" compilation error.
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);
b = 2;
System.out.println("case 1 after: b = " + b);
break;
default:
b = 7;
System.out.println("default: b = " + b);
}
Note: the above code compiles with a java 1.6 compiler.
Do not declare variables inside a switch statement before the first case label. According to the C Standard, 6.8.
Declaring a variable inside a switch block is fine. Declaring after a case guard is not.
Case ranges and case labels can be freely intermixed, and multiple case ranges can be specified within a switch statement.
A switch works with the byte , short , char , and int primitive data types.
The scope of b
is the block. You have only one block which includes all case
s. That's why you get a compile error when you redeclare b
in your second case
.
You could wrap each case
in an own block like
case 0:
{
int b = 1;
...
}
case 1:
{
int b = 2;
...
}
but I think FindBugs or CheckStyle would complain about that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With