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?
Declaring a variable inside a switch block is fine. Declaring after a case guard is not.
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.
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.
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).
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With