Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are references declared in a switch statement?

To my surprise this code works fine:

int i = 2;
switch(i) {
case 1:
    String myString = "foo";
    break;
case 2:
    myString = "poo";
    System.out.println(myString);
}

But the String reference should never be declared? Could it be that all variables under every case always are declared no matter what, or how is this resolved?

like image 981
pgsandstrom Avatar asked Jun 17 '10 07:06

pgsandstrom


People also ask

Can you declare variables in a switch statement?

Declaring a variable inside a switch block is fine. Declaring after a case guard is not.

When should you use switch statement?

Switch statements are cleaner syntax over a complex or stacked series of if else statements. Use switch instead of if when: You are comparing multiple possible conditions of an expression and the expression itself is non-trivial. You have multiple values that may require the same code.

How do switch statements work?

The body of a switch statement is known as a switch block. A statement in the switch block can be labeled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label.


2 Answers

Well, it's about brackets (i.e. scope).

It's better practice, arguably, to write your statements like so:

int i = 2;
switch(i) {
    case 1: {
        String myString = "foo";
        break;
    }
    case 2: {
        myString = "poo";
        System.out.println(myString);
    }
}

(I'm not near a Java compiler right now, but that shouldn't compile).

like image 169
Noon Silk Avatar answered Sep 21 '22 16:09

Noon Silk


The scope of the myString declaration is the switch block (where the { character is). If you were to write it like this, the declaration would be per-case:

int i = 2;
switch(i) {
    case 1: {
        String myString = "foo";
        break;
    }

    case 2: {
        String myString = "poo";
        System.out.println(myString);
    }
}
like image 30
Gerco Dries Avatar answered Sep 23 '22 16:09

Gerco Dries