Labeled statement in java
The scope of a label is the immediately contained statement after the label.
Execute a label executes the contained statement or the following statment in another word.
label:
statement
Label should work with break and continue to make an impact. Break a label will stop execution immediately. Continue a label will stop current loop and execute next loop. Note that break can work with if statement, whereas continue must work with loops. See below example.
public class LabelTest {
public static void main(String ...args) {
// a raw label statement
l1:
System.out.println("label statement");
l2:
for(int i=0;i<3;i++)
for(int j=0;j<3;j++) {
if(j == 1) {
// continue to l2, continue from outer loop
continue l2;
}
// output:
// 0 0
// 1 0
// 2 0
System.out.println(i + " " + j);
}
l3:
for(int i=0;i<3;i++)
for(int j=0;j<3;j++) {
if(j == 1) {
// break to l3, break entire loop
break l3;
}
// output:
// 0 0
System.out.println(i + " " + j);
}
l4:
if(true) {
System.out.println("break if");
break l4;
}
}
}