Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why object declared after one case label is available in others? [duplicate]

Tags:

java

Possible Duplicate:
Variable scope in a switch case

I've got a code like this:

switch(a) {
case b:
 Object o = new Object();
 return o;
case c:
 o = new Object();
 return o;
 }

and i'm interesting why it's possible to use variable declared after first case label in the second one even if first state will never be reached?

like image 665
amukhachov Avatar asked May 18 '11 08:05

amukhachov


1 Answers

Despite being in different cases, the variables local to the switch statement are in the same block, which means they are in the same scope.

As far as I know, new scope in Java is only created in a new block of code. A block of code (with more than one line) has to be surrounded by curly braces. The code in the cases of a switch statement is not surrounded by curly braces, so it is part of the whole statement's scope.

However, you can actually introduce a new scope to the statement by adding curly braces:

switch (cond) {
case 1:{
     Object o = new Object();
}
    break;
case 2:{
    // Object o is not defined here!
}
    break;
}
like image 195
Tikhon Jelvis Avatar answered Oct 17 '22 07:10

Tikhon Jelvis