Java Examples - Label
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
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
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: 2Other Extensions
Java Examples