Varun Jain
Varun Jain

Reputation: 91

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

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;
        }
    }
}

Upvotes: 4

Views: 11302

Answers (1)

sanbhat
sanbhat

Reputation: 17622

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;
}

Upvotes: 2

Related Questions