Switch statements are mostly odd in terms of scope. From section 6.3 JLS :
The declaration volume of a local variable in a block (ยง14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any other declarators on the right in the statement for declaring the local variable.
In your case, case 2 is in the same block as case 1 and appears after it, although case 1 will never be executed ... therefore the local variable is in scope and is writable even though you logically never Do not follow up on the declaration. (The declaration is not "executable," although initialization is.)
If you comment out the purpose of value = 2; , the compiler still knows which variable you are accessing, but you will not go through any execution path that assigns a value to it, so you get an error like you would try to read any other undefined local variable.
I would strongly recommend that you not use local variables declared in other cases - this leads to very confusing code, as you saw. When I introduce local variables into 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 think this is clearer.
Jon Skeet May 30 '12 at 6:12 2012-05-30 06:12
source share