When are the references in the switch statement?

To my surprise, this code works just fine:

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

But should a String reference never be declared? Could it be that all variables in each case are always declared no matter what or how it is allowed?

+7
java switch-statement
source share
2 answers

Well, this is about brackets (i.e. areas).

It is better to practice, perhaps write your statements like this:

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

(I'm not right next to the Java compiler, but this should not compile).

+7
source share

The declaration scope myString is a switch block (where the symbol is {). If you must write it like this, the declaration will be in each case:

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

All Articles