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;
}
Share:
10,549

Related videos on Youtube

Varun Jain
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, 2022

Comments

  • Varun Jain
    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
    Varun Jain almost 11 years
    I tried exactly what you suggested but it still shows undefined label error.
  • sanbhat
    sanbhat almost 11 years
    have you added braces after the Sysout statement and have done break first; inside those braces?
  • Varun Jain
    Varun Jain almost 11 years
    Yes for loop should be inside the first:{}. It works fine, Curly braces was needed. But is there a way to do this:
  • Varun Jain
    Varun Jain almost 11 years
    But is there a way to do this: exit first: label with break first; being in other loop?