Variable's scope in a switch case [duplicate]
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 case
clause corresponds to the whole switch
statement. You can, however, create further nested scopes with braces as follows:
int key = 2;
switch (key) {
case 1: {
String str = "1";
return str;
}
case 2: {
String str = "2";
return str;
}
}
The resulting code will now compile successfully since the variable named str
in each case
clause is in its own scope.
The scope of the variable is the whole switch
statement -- all cases and default, if included.
Here are some other options...
Option 1:
int key = 2;
switch (key) {
case 1:
return "1";
case 2:
return "2";
}
Option 2:
int key = 2;
String str = null;
switch (key) {
case 1:
str = "1";
return str;
case 2:
str = "2";
return str;
}