Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does java scope declarations in switch case statements? [duplicate]

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?

like image 960
CMfly Avatar asked Feb 26 '15 16:02

CMfly


2 Answers

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.

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.

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;
    ...
}
like image 158
Jon Skeet Avatar answered Oct 12 '22 23:10

Jon Skeet


case itself does not declare scope. Scope is limited by { and }. So, your variable y is defined in outer scope (of whole switch) and updated in inner scope (of case 5).

like image 20
AlexR Avatar answered Oct 13 '22 01:10

AlexR