Method Label
# Java Example - Label
[ Java Example](#)
In Java, a label is an identifier used to mark a code block, typically used with loop statements (such as for, while, do-while) and branch statements (such as if-else, switch).
The syntax of a label is to add an identifier before the code block followed by a colon, for example:
labelName:
To break out of the code block marked by a label, you can use the break or continue statement with the label.
The following example demonstrates how to use a label with the break statement to break out of an outer loop:
## Main.java file
public class Main{public static void main(String[]args){outerLoop: for(int i = 0; i<3; i++){innerLoop: for(int j = 0; j<3; j++){if(i == 1&&j == 1){break outerLoop; // break outer loop}System.out.println("i: " + i + ", j: " + j); }}}}
In the above code, the outer loop iterates with variable i ranging from 0 to 2, and the inner loop iterates with variable j also ranging from 0 to 2. When i equals 1 and j equals 1, the break outerLoop; statement is executed, breaking out of the outer loop. Otherwise, the current values of i and j are printed.
The output of the above code is:
i: 0, j: 0 i: 0, j: 1 i: 0, j: 2
The following example demonstrates how to use a label with the continue statement to control loops:
## Example
public class Main{public static void main(String[]args){outerLoop: for(int i = 0; i<3; i++){innerLoop: for(int j = 0; j<3; j++){if(i == 1&&j == 1){continue outerLoop; // jump
YouTip