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