tags:

views:

66

answers:

6

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

+4  A: 

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;
}
Drew Wills
A: 

Several cases can be executed in one switch statement. So..

Stas
A: 

The scope of a variable exists between the braces of the switch and if statements. In example Code 1 the switch braces enclose both declarations of the variables which will cause the compiler to error as the name to variable binding will have already been made.

In the other example it is ok because both variables are declared within their own braces (scope).

JC
A: 

You seem to be assuming that each case is a block with its own local scope, as if/else blocks. It's not.

It's important to correct this conceptual mistake, because otherwise you'll end falling in the frequent trap of forgetting the break inside the case

leonbloy
A: 

In the first case the scope of the String declaration is within the switch statement therefore it is shown as duplicate while in the second the string is enclosed within curly braces which limits the scope within the if/else conditions,therefore it is not an error in the second case.

Emil
+4  A: 

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.

Richard Cook
Listen to this guy. He's right.
John