Variable's scope in a switch case

Philippe Carriere picture Philippe Carriere · Oct 8, 2010 · Viewed 39.6k times · Source

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

Answer

Richard Cook picture Richard Cook · Oct 8, 2010

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.