Error: undefined label, how to use label statement in this code in java?

I read in Java tutorials that any statement can be tagged and can be used with break. But when I try this code, I get an undefined error label. (The guys at stackoverflow wait before marking this question as a duplicate, I checked these questions, but none of them explained this problem).

public class LabelTest { public static void main(String[] args) { first: System.out.println("First statement"); for (int i = 0; i < 2; i++) { System.out.println("Second statement"); break first; } } } 
+4
source share
1 answer

According to JLS 14.7

The label area of ​​a labeled statement is the one immediately containing the expression.

So, in your case, the scope of the first is the sysout statement following the table. To be more precise, you can define the scope using curly braces, and within these curly brackets it is valid for going to the label. So below is acceptable

 first: { System.out.println("First statement"); for (int i = 0; i < 2; i++) { System.out.println("Second statement"); break first; } } 

OR

 first: { System.out.println("First statement"); break first; } second: for(int i=0;i<2;i++){ System.out.println("Second statement"); break second; } 
+2
source

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


All Articles