Why is an object declared after one case label available in others?

Possible duplicate:
Variable scope in case of switch

I have a code like this:

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

and I wonder why you can use the variable declared after the label of the first case in the second, even if the first state is never reached?

+6
source share
1 answer

Despite the fact that in different cases the variables local to the switch are in the same block, which means that they are in the same area.

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

However, you can enter a new area in the statement by adding curly braces:

 switch (cond) { case 1:{ Object o = new Object(); } break; case 2:{ // Object o is not defined here! } break; } 
+2
source

Source: https://habr.com/ru/post/888395/


All Articles