Java – Label Statement
The label statement is used in conjunction with the break and continue statements. It is used to preface a statement with a referential identifier. In Java, a label can be supplied by any name that is not one of the reserved terms. The following is the syntax for using label:
Syntax
label : statements;
Label statement with Continue statement
A loop is identified by a label, and the continue statement is used to signal when the current iteration should be skipped.
public class MyClass { public static void main(String[] args) { loop1 : for (int i = 1; i <= 5; i++){ if(i == 3) continue loop1; System.out.println("i = " + i); } } }
The output of the above code will be:
i = 1 i = 2 i = 4 i = 5
When the requirements are satisfied in the example below, the label statement is used to bypass the inner and outer loops, respectively.
public class MyClass { public static void main(String[] args) { System.out.println("#Skips the inner loop"); loop1 : for (int i = 1; i <= 3; i++){ loop2 : for (int j = 1; j <= 3; j++){ if(i == 2 && j == 2) continue loop2; System.out.println("i = " + i + ", j = " + j); } } System.out.println("\n#Skips the outer loop"); loop3 : for (int i = 1; i <= 3; i++){ loop4 : for (int j = 1; j <= 3; j++){ if(i == 2 && j == 2) continue loop3; System.out.println("i = " + i + ", j = " + j); } } } }
The output of the above code will be:
#Skips the inner loop i = 1, j = 1 i = 1, j = 2 i = 1, j = 3 i = 2, j = 1 i = 2, j = 3 i = 3, j = 1 i = 3, j = 2 i = 3, j = 3 #Skips the outer loop i = 1, j = 1 i = 1, j = 2 i = 1, j = 3 i = 2, j = 1 i = 3, j = 1 i = 3, j = 2 i = 3, j = 3
Label statement with a Break statement
A loop is identified by a label, which is followed by a break statement that indicates when to exit the loop.
public class MyClass { public static void main(String[] args) { loop1 : for (int i = 1; i <= 5; i++){ if(i == 3) break loop1; System.out.println("i = " + i); } } }
The output of the above code will be:
i = 1 i = 2
When the requirements are satisfied in the example below, the label statement is used to bypass the inner and outer loops, respectively.
public class MyClass { public static void main(String[] args) { System.out.println("#Breaks from the inner loop"); loop1 : for (int i = 1; i <= 3; i++){ loop2 : for (int j = 1; j <= 3; j++){ if(i == 2 && j == 2) break loop2; System.out.println("i = " + i + ", j = " + j); } } System.out.println("\n#Breaks from the outer loop"); loop3 : for (int i = 1; i <= 3; i++){ loop4 : for (int j = 1; j <= 3; j++){ if(i == 2 && j == 2) break loop3; System.out.println("i = " + i + ", j = " + j); } } } }
The output of the above code will be:
#Breaks from the inner loop i = 1, j = 1 i = 1, j = 2 i = 1, j = 3 i = 2, j = 1 i = 3, j = 1 i = 3, j = 2 i = 3, j = 3 #Breaks from the outer loop i = 1, j = 1 i = 1, j = 2 i = 1, j = 3 i = 2, j = 1
To run any of the above codes: Click Here.