Java switch : variable declaration and scope

Marius Ion picture Marius Ion · Jun 7, 2012 · Viewed 7.4k times · Source

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.

Answer

aioobe picture aioobe · Jun 7, 2012

The scope is, just as usual, delimited by { and }.