break abc in java; what grammar is this?

Asked 2 years ago, Updated 2 years ago, 103 views

class CodeRunner{
    public static void main(String[] args){
        abc:
        for(int i=0; i<10; i++){
            for(int j=i+1;j<20;j++){
                if(i+j==5){
                    System.out.println(i+j);
                    break abc;
                }
            }
        }
    }
}

I saw this code in Java. It's my first time seeing something come up like abc after break. When do you use it? When I removed abc: in the third line, the error message undefined label: abc appears.

java syntax

2022-09-22 20:18

1 Answers

It's called label. Skips the block of the specified label when using the label.

In general, when using overlapping repetitive statements, break the number of overlapping repetitive statements to escape the loop. However, if you use the label, you can exit all loops at once by specifying breakableName; once under the desired conditions. Below is a simple example.

class CodeRunner {
    public static void main(String[] args) {

        for (int i = 0; ; i++) {
            for (int j = 0; ; j++) {
                for (int k = 0; ; k++) {
                    if (k == 3) break;
                }
                break;
            }
            break;
        }

        breakLabel:
        for (int i = 0; ; i++) {
            for (int j = 0; ; j++) {
                for (int k = 0; ; k++) {
                    if (k == 3) break breakLabel;
                }
            }
        }
        //If you meet breakbreakLabel, run from here

    }
}


2022-09-22 20:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.