I think I don’t understand how the scope works in a switch case.
Can someone explain to me why the first code doesn’t compile but the second does ?
Code 1 :
int key = 2;
switch (key) {
case 1:
String str = "1";
return str;
case 2:
String str = "2"; // duplicate declaration of "str" according to Eclipse.
return str;
}
Code 2 :
int key = 2;
if (key == 1) {
String str = "1";
return str;
} else if (key == 2) {
String str = "2";
return str;
}
How come the scope of the variable “str” is not contained within Case 1 ?
If I skip the declaration of case 1 the variable “str” is never declared…
I’ll repeat what others have said: the scope of the variables in each
caseclause corresponds to the wholeswitchstatement. You can, however, create further nested scopes with braces as follows:The resulting code will now compile successfully since the variable named
strin eachcaseclause is in its own scope.Also note that the scope for
case:(sans-{}) goes to the ‘global’switchscope. And after that every othercasescope (with or without{}) will receive those variables in a way uncommon for nested java scope, they can’t be overridden. So, for example, adding{}only to the secondcasewould still give you the same error as it would get the variable from the first one injected, but adding braces to the first one would compile. I am not sure this is defined as such on the spec, but it what happens on most implementations.