Declaring and initializing variables within Java switches

namalfernandolk picture namalfernandolk · May 30, 2012 · Viewed 15.9k times · Source

I have a crazy question about Java switches.

int key = 2;

switch (key) {
    case 1:
        int value = 1;
        break;
    case 2:
        value = 2;
        System.out.println(value);
        break;
    default:
        break;
}

Scenario 1 - When the key is two it successfully print the value as 2.
Scenario 2 - When I'm going to comment value = 2 in case 2: it squawks saying the The local variable value may not have been initialized.

Questions :

Scenario 1 : If the execution flow doesn't go to case 1: (when the key = 2), then how does it know the type of the value variable as int?

Scenario 2 : If the compiler knows the type of the value variable as int, then it must have accessed to the int value = 1; expression in case 1:.(Declaration and Initialization). Then why does it sqawrk When I'm going to comment value = 2 in case 2:, saying the The local variable value may not have been initialized.

Answer

Jon Skeet picture Jon Skeet · May 30, 2012

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.