** 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 **?
** 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. ** **
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...
}
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 ...