Variable’s scope in a switch case [duplicate]

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.

Leave a Comment