[JAVA] Can statements other than loops be labeled?

problem

** Labels ** in Java are usually attached to loop statements (do statement, for statement, while statement).

LOOP1:for (String str1 : list1) { //Labeled for statement
    for (String str2 : list2) {
        if (str1.equals(str2)) {
            found(str1);
            break LOOP1; //Exit from the outer for
        }
    }
}

So is it possible to label statements other than loop statements **?

  1. Statements other than loop statements cannot be labeled (a compilation error will occur).
  2. In some cases, a statement other than the loop statement can be labeled, but it is meaningless after all because the statement that refers to the label cannot be written.
  3. In some cases, statements other than loop statements can be labeled, and in some cases, statements that refer to the label can be written.

jaba-2.png

Correct answer

** 3. In some cases, a statement other than the loop statement can be labeled, and in some cases, a statement that refers to the label can be written. ** **

Commentary

Most Java statements can be labeled.

//Labeled expression!
FOO: a = 42; // OK
//Labeled if statement!
BAR: if (a > 0) b = 1;
else b = -1; // OK

[^ statement-1]: In the format definition in the Java language specification, the statement corresponding to "Statement" is labeled. A local variable declaration statement (“LocalVariableDeclarationStatement”) is not a type of “Statement”.

Compile error


//Labeled variable declaration statement??
FOO: int a = 42; // NG!

Then, when the block statement and the control statement (including not only the loop but also the if statement and try statement) to which the block statement is subordinate are labeled (for example, LABEL:), break is added in the block. You can escape from the statement with LABEL:by executing LABEL;.

FOO: if (val > 1000) { //Labeled if statement!
    big = true;
    if (val % 2 == 0) break FOO; //Exit the block
    bigOdd = true;
}

For example, it can be used when you want to "early escape" to a specific area in a function.

BLOCK:{ //Plain block
    Foo foo1 = stor.findFoo(fooName1);
    if (foo1 == null)
        break BLOCK; //Exit the block
    Foo foo2 = stor.findFoo(fooName2);
    if (foo2 == null)
        break BLOCK; //Exit the block

    foo2.setBar(foo1.getBar());
    //After that, the process continues endlessly...
}

Supplement

Serpentine

Actually, it seems that you can write a break statement that refers to a label attached to a statement without blocks.

FOO: break FOO; // OK!!!!

Well, it's not useful at all ...

Recommended Posts

Can statements other than loops be labeled?
Scala String can be used other than java.lang.String method
Ruby array methods that can be used with Rails (other than each)