111

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.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
ironwood
  • 8,936
  • 15
  • 65
  • 114
  • 16
    It's not a crazy question, it's a very good question. – biziclop May 30 '12 at 10:55
  • Possible duplicate of [Variable's scope in a switch case](http://stackoverflow.com/questions/3894119/variables-scope-in-a-switch-case) – Philippe Carriere Jun 13 '16 at 19:45
  • @PhilippeCarriere Actually, I think it should be in reverse - the answer here is better (even if the post is newer) since there's a direct reference to the JLS, and summarizes well the issue covered in different answers in that post. [See also](http://meta.stackoverflow.com/questions/251938/should-i-flag-a-question-as-duplicate-if-it-has-received-better-answers). – Tunaki Jun 13 '16 at 19:54
  • @Tunaki The description for a duplicate starts with "This question has been asked before". I'm reading that as the later one should be marked as a duplicate of the earlier one. But I do agree that this one has nice elements. Maybe they should be merged somehow? – Philippe Carriere Jun 13 '16 at 21:34
  • Also a lot of questions on SO are marked as duplicate of my original question, so if you decide that it's better to mark this one as the new original, please fix all the links to refer to this one instead of mine. – Philippe Carriere Jun 13 '16 at 21:47

6 Answers6

121

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 11
    +1 for "A declaration isn't really "executable" although initialization is.". And thank you for the advises too Skeet. – ironwood May 30 '12 at 06:29
  • 1
    With the JEP-325 integrated, the [picture of the scope of local variables has changed](https://stackoverflow.com/a/52238424/1746118) and one can use the same name across cases instead of switch blocks. Though it relies on similar block coding as well. Also, the value assigned to a variable per switch case would be much convenient with the switch expressions. – Naman Sep 08 '18 at 18:59
  • 1
    Points for adding a new scope with braces. Didn't even know you could do that. – Floating Sunfish Dec 11 '18 at 08:09
22

The variable has been declared (as an int), but not initialized (assigned an initial value). Think of the line:

int value = 1;

As:

int value;
value = 1;

The int value part tells the compiler at compile time that you have a variable called value which is an int. The value = 1 part initializes it, but that happens at run-time, and doesn't happen at all if that branch of the switch isn't entered.

Paul
  • 139,544
  • 27
  • 275
  • 264
18

From http://www.coderanch.com/t/447381/java-programmer-SCJP/certification/variable-initialization-within-case-block

Declarations are processed at compile time and do not depend on the execution flow of your code. Since value is declared within the local scope of the switch block, it is useable anywhere in that block from the point of its declaration.

Garbage
  • 1,490
  • 11
  • 23
5

With the integration of JEP 325: Switch Expressions (Preview) in JDK-12 early access builds. There are certain changes that could be seen from Jon's answer -

  1. Local Variable Scope - The local variables in the switch cases can now be local to the case itself instead of the entire switch block. An example (similar to what Jon had attempted syntactically as well) considering the Day enum class for further explanation :

    public enum Day {
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
    }
    
    // some another method implementation
    Day day = Day.valueOf(scanner.next());
    switch (day) {
        case MONDAY,TUESDAY -> {
            var temp = "mon-tue";
            System.out.println(temp);
        }
        case WEDNESDAY,THURSDAY -> {
            var temp = Date.from(Instant.now()); // same variable name 'temp'
            System.out.println(temp);
        }
        default ->{
            var temp = 0.04; // different types as well (not mandatory ofcourse)
            System.out.println(temp);
        }
    }
    
  2. Switch Expressions - If the intent is to assign a value to a variable and then make use of it, once can make use of the switch expressions. e.g.

    private static void useSwitchExpression() {
        int key = 2;
        int value = switch (key) {
            case 1 ->  1;
            case 2 -> 2;
            default -> {break 0;}
        };
        System.out.println("value = " + value); // prints 'value = 2'
    }
    
Naman
  • 27,789
  • 26
  • 218
  • 353
0

This Explanation might help.

    int id=1;

    switch(id){
        default: 
            boolean b= false; // all switch scope going down, because there is no scope tag

        case 1:
            b = false;
        case 2:{
            //String b= "test"; you can't declare scope here. because it's in the scope @top
            b=true; // b is still accessible
        }
        case 3:{
            boolean c= true; // case c scope only
            b=true; // case 3 scope is whole switch
        }
        case 4:{
            boolean c= false; // case 4 scope only
        }
    }
Java jansen
  • 187
  • 2
  • 15
0

Java spec:

https://docs.oracle.com/javase/specs/jls/se12/html/jls-14.html#jls-14.11

The case of abrupt completion because of a break with a label is handled by the general rule for labeled statements (§14.7).

https://docs.oracle.com/javase/specs/jls/se12/html/jls-14.html#jls-14.7

Labeled statements:

LabeledStatement: Identifier : Statement

LabeledStatementNoShortIf: Identifier : StatementNoShortIf

Unlike C and C++, the Java programming language has no goto statement; identifier statement labels are used with break (§14.15) or continue (§14.16) statements appearing anywhere within the labeled statement.

The scope of a label of a labeled statement is the immediately contained Statement.

In other words, case 1, case 2 are labels within the switch statement. break and continue statements can be applied to labels.

Because labels share the scope of the statement, all variables defined within labels share the scope of the switch statement.

Pavel Molchanov
  • 2,299
  • 1
  • 19
  • 24