Labeled break and continue help you control loops more precisely by naming them. This lets you jump out of or skip parts of outer loops easily.
Labeled break and continue in Java
labelName: for (initialization; condition; update) { // loop body if (condition) { break labelName; // exits the labeled loop // continue labelName; // skips to next iteration of labeled loop } }
The label is an identifier followed by a colon placed before the loop.
Use break labelName; to exit the labeled loop immediately.
Use continue labelName; to skip to the next iteration of the labeled loop.
outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { break outer; } System.out.println(i + "," + j); } }
outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (j == 1) { continue outer; } System.out.println(i + "," + j); } }
This program uses labeled break and continue to control nested loops. It breaks out of both loops when i=2 and j=2, and skips to the next outer loop iteration when j=3.
public class LabeledBreakContinue { public static void main(String[] args) { outer: for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (i == 2 && j == 2) { System.out.println("Breaking out of outer loop at i=2, j=2"); break outer; } if (j == 3) { System.out.println("Skipping rest of outer loop iteration when j=3"); continue outer; } System.out.println("i=" + i + ", j=" + j); } } System.out.println("Loops ended."); } }
Labels must be unique identifiers placed before loops.
Using labeled break and continue can make nested loop control simpler and clearer.
Overusing labels can make code harder to read, so use them only when needed.
Labeled break and continue let you jump out of or skip iterations of outer loops from inside inner loops.
They help manage nested loops without extra flags or complicated logic.
Use labels carefully to keep code clear and easy to understand.