A labelled loop in Java allows you to specify which loop to break or continue when dealing with nested loops. This makes it easier to control the flow of execution in complex scenarios.
Syntax
1 2 3 4 5 6 7 |
label_name: for (initialization; condition; update) { // loop body if (someCondition) { break label_name; // or continue label_name; } } |
Here, label_name
is the label given to the loop, and you use break
or continue
with the label to control flow.
- Labelled loops help manage the flow of control in nested loops.
break label_name;
exits the loop with the specified label.continue label_name;
skips the remaining code in the loop with the specified label and moves to the next iteration.
Examples
- Using a labelled break
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class LabelledLoopExample { public static void main(String[] args) { outerLoop: // Label for the outer loop for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i == 2 && j == 3) { break outerLoop; // Breaks out of the outer loop when i=2 and j=3 } System.out.println("i = " + i + ", j = " + j); } } } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 |
i = 0, j = 0 i = 0, j = 1 i = 0, j = 2 i = 0, j = 3 i = 0, j = 4 i = 1, j = 0 i = 1, j = 1 i = 1, j = 2 i = 1, j = 3 i = 1, j = 4 i = 2, j = 0 i = 2, j = 1 i = 2, j = 2 |
- Using a labelled continue
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class LabelledContinueExample { public static void main(String[] args) { outerLoop: // Label for the outer loop for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i == 2 && j == 3) { continue outerLoop; // Skips the rest of the inner loop and continues with the next iteration of the outer loop } System.out.println("i = " + i + ", j = " + j); } } } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 |
i = 0, j = 0 i = 0, j = 1 i = 0, j = 2 i = 0, j = 3 i = 0, j = 4 i = 1, j = 0 i = 1, j = 1 i = 1, j = 2 i = 1, j = 3 i = 1, j = 4 i = 2, j = 0 i = 2, j = 1 i = 2, j = 2 |