6

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?

CMfly
  • 103
  • 5
  • I believe the variable is declared in the scope of entire switch and not just the case. I'm not sure of it but i think that is what is happening. โ€“ StackFlowed Feb 26 '15 at 16:24
  • 1
    Similar question was raised before: http://stackoverflow.com/questions/10810768/declaring-and-initializing-variables-within-java-switches โ€“ DonatasD Feb 26 '15 at 16:24
  • 1
    hope this link will answer for your question http://stackoverflow.com/questions/3894119/variables-scope-in-a-switch-case โ€“ Girish Bhat M Feb 26 '15 at 16:27

3 Answers3

9

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;
    ...
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

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).

AlexR
  • 114,158
  • 16
  • 130
  • 208
0

As I know is the complete switch statement one scope. Without a break; or return; statement other switch cases would be interpreted, too. So when you define a variable inside the switch statement it is visible in the hole switch case.

Rene M.
  • 2,660
  • 15
  • 24