break with Labels: Exiting Nested Loops
What you'll learn: How to use labeled break statements to exit multiple nested loops at once, instead of breaking just the innermost loop.
Why Labels Matter in Nested Loops
You've learned that break exits the current loop. But what if you're two or three loops deep and need to escape all of them at once? Normally, break only exits the innermost loop—you'd need multiple break statements and flag variables to escape outer loops. That's messy.
Labels provide a cleaner solution. A label is simply an identifier followed by a colon, placed before a loop. When you write break labelName;, Java jumps out of the labeled loop directly, no matter how many loops deep you are.
The Syntax
outerLoop:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
break outerLoop; // Exits BOTH loops
}
System.out.println(i + "," + j);
}
}
System.out.println("Done");
Output:
0,0
0,1
0,2
1,0
Done
When i is 1 and j is 1, break outerLoop; exits the entire outer loop immediately—no further iterations of either loop occur.
Think of It Like This
Imagine you're in a building with rooms inside rooms. A regular break walks you out of your current room. A labeled break is like having an emergency exit sign that takes you directly outside the building, skipping all intermediate rooms.
When to Use
Labeled breaks are perfect for search algorithms in nested structures: once you find what you're looking for, you can escape all loops cleanly without awkward flag variables.
Key Takeaway: Labeled break statements let you exit multiple nested loops in one clean statement by breaking to a specific outer label.