0Pricing
Java Academy · Lesson

Labeled break

Exit outer loops cleanly.

The Problem with Nested Loops

A plain break only exits the inner loop. But often you want to leave both loops at once.

Imagine searching a grid for one value. Once you find it, you want to stop everything, not just the inner loop.

Java solves this with a labeled break.

What Is a Label?

A label is a name you attach to a loop, followed by a colon.

For example outer: placed just before a for loop names that loop "outer".

Labels by themselves do nothing. They become useful when paired with break or continue.

outer:
for (int i = 0; i < 3; i++) {
    // 'outer' is now a name for this loop
}

All lessons in this course

  1. break and continue
  2. Labeled break
  3. Labeled continue
  4. Avoiding Spaghetti Flow
← Back to Java Academy