0
0
Javaprogramming~7 mins

Labeled break and continue in Java

Choose your learning style9 modes available
Introduction

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.

When you have nested loops and want to stop or skip the outer loop from inside the inner loop.
When you want to avoid complicated flags or extra checks to control multiple loops.
When you want clearer and simpler code to handle complex loop exit or skip conditions.
Syntax
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.

Examples
This breaks out of both loops when i and j are both 1.
Java
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);
    }
}
This skips the rest of the inner loop and continues the next iteration of the outer loop when j is 1.
Java
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);
    }
}
Sample Program

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.

Java
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.");
    }
}
OutputSuccess
Important Notes

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.

Summary

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.