How are java declarations in switch statement statements?

The following Java code runs without errors in Java 1.7

public static void main(String[] args) { int x = 5; switch(x) { case 4: int y = 3423432; break; case 5: { y = 33; } } } 

How java finds out that y is an int since the declaration never starts. Does the declaration of variables in the case expression point to the level of the switch statement when curly braces are not used in the case case?

+6
source share
3 answers

Declarations do not run - they are not what you need to execute, they just tell the compiler the type of the variable. (The initializer will work, but that's fine - you are not trying to read from the variable before assigning it a value.)

The accumulation inside switch statements is definitely odd, but basically the variable declared in the first case is still in scope in the second case .

From section 6.3 JLS :

The declaration volume of a local variable in a block (ยง14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any other declarators on the right in the statement for declaring the local variable.

If you do not create additional blocks, the entire switch statement will be a single block. If you want to create a new area for each case, you can use curly braces:

 case 1: { int y = 7; ... } case 2: { int y = 5; ... } 
+9
source

the case itself does not declare the area. The scope is limited to { and } . Thus, your variable y is defined in the outer region (of the entire switch) and updated in the inner region ( case 5 ).

+1
source

As I know, this is a complete switch one scope statement. No break; or return; the expression of other switching cases will also be interpreted. Therefore, when you define a variable inside the switch statement, it is visible in the hole switch enclosure.

0
source

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


All Articles