views:

56

answers:

2

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?

+7  A: 

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

Noon Silk
I learned something new today!
abhin4v
Indeed it doesn't compile.
musiKk
@musikk: Thanks for confirming, it's not often I'm happy that something doesn't compile :)
Noon Silk
It's interesting... you don't think about it much, but you can further limit the scope of certain variables arbitrarily by using braces...
Tim Bender
+3  A: 

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);
    }
}
Gerco Dries