Switch statements are odd in terms of scoping, basically. From section 6.3 of the JLS:
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.
In your case, case 2
is in the same block as case 1
and appears after it, even though case 1
will never execute... so the local variable is in scope and available for writing despite you logically never "executing" the declaration. (A declaration isn't really "executable" although initialization is.)
If you comment out the value = 2;
assignment, the compiler still knows which variable you're referring to, but you won't have gone through any execution path which assigns it a value, which is why you get an error as you would when you try to read any other not-definitely-assigned local variable.
I would strongly recommend you not to use local variables declared in other cases - it leads to highly confusing code, as you've seen. When I introduce local variables in switch statements (which I try to do rarely - cases should be very short, ideally) I usually prefer to introduce a new scope:
case 1: {
int value = 1;
...
break;
}
case 2: {
int value = 2;
...
break;
}
I believe this is clearer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…