error:undefined label, how to use label statement in this code in java?
10,549
As per JLS 14.7
The scope of a label of a labeled statement is the immediately contained Statement.
So in your case, the scope of lable first
is the sysout
statement following the lable. To be clearer, you can define the scope using curly braces, and within these braces its valid to jump to the label. So below are valid
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;
}
Related videos on Youtube
![Varun Jain](https://i.stack.imgur.com/5h4ZR.jpg?s=256&g=1)
Author by
Varun Jain
Im into website development in and out. If you need to build your website, then let me know.
Updated on June 04, 2022Comments
-
Varun Jain about 2 years
I read in textbooks for Java that any statement can be labeled and can be used with break. But while trying this code i get error undefined label. (Guys at stackoverflow wait before marking this question as duplicate, i have checked those questions but none of those explain 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; } } }
-
Varun Jain almost 11 yearsI tried exactly what you suggested but it still shows undefined label error.
-
sanbhat almost 11 yearshave you added braces after the Sysout statement and have done
break first;
inside those braces? -
Varun Jain almost 11 yearsYes for loop should be inside the first:{}. It works fine, Curly braces was needed. But is there a way to do this:
-
Varun Jain almost 11 yearsBut is there a way to do this: exit first: label with break first; being in other loop?