Java Examples - Label

Java 实例Java Examples

In Java, a label is an identifier used to mark a block of code, and is usually used with loop statements (e.g., for, while, do-while) and branch statements (e.g., if-else, switch).

The syntax of a label is to add an identifier before a code block and end with a colon, for example:

labelName:

To exit the code block marked by the label, you can use a break or continue statement followed by the label.

The following example demonstrates how to use a label combined with a break statement to exit the 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; //Exit the outer loop } System.out.println("i: " + i + ", j: " + j); } } } }

In the above code, the outer loop iteration variable i ranges from 0 to 2, and the inner loop iteration variable j also ranges from 0 to 2. When i equals 1 and j equals 1, executebreak outerLoop;statement, which breaks out of the outer loop. Otherwise, the values of i and j for the current iteration are output.

The above code produces the following output:

i: 0, j: 0
i: 0, j: 1
i: 0, j: 2

The following example demonstrates how to use a label combined with a continue statement to control a loop:

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; //Skip the current iteration of the outer loop } System.out.println("i: " + i + ", j: " + j); } } } }

In the above code, the outer loop iteration variable i ranges from 0 to 2, and the inner loop iteration variable j also ranges from 0 to 2. When i equals 1 and j equals 1, executecontinue outerLoop;statement, skipping the current iteration of the outer loop. Otherwise, the values of i and j for the current iteration are output.

The above code produces the following output:

i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
i: 1, j: 0
i: 2, j: 0
i: 2, j: 1
i: 2, j: 2

Java 实例Java Examples

Other Extensions