The following java code executes without error in Java 1.7
public static void main(String[] args) {
int x = 5;
switch(x) {
case 4:
int y = 3423432;
break;
case 5: {
y = 33;
}
}
}
How does java figure out that y is an int since the declaration never gets run. Does the declaration of variables within a case statement get scoped to the switch statement level when braces are not used in a case statement?
解决方案
Declarations aren't "run" - they're not something that needs to execute, they just tell the compiler the type of a variable. (An initializer would run, but that's fine - you're not trying to read from the variable before assigning a value to it.)
Scoping within switch statements is definitely odd, but basically the variable declared in the first case is still in scope in the second case.
The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any further declarators to the right in the local variable declaration statement.
Unless you create extra blocks, the whole switch statement is one block. If you want a new scope for each case, you can use braces:
case 1: {
int y = 7;
...
}
case 2: {
int y = 5;
...
}