Labeled Statements: Syntax and Purpose
What You'll Learn
You'll learn how to put labels on loops so you can control exactly which loop to break or continue when you have loops inside loops.
The Problem with Nested Loops
When you nest loops (a loop inside another loop), a regular break or continue only affects the innermost loop. But what if you need to jump out of the outer loop from deep inside? That's where labeled statements come in.
Labeled Statement Syntax
A label is simply an identifier followed by a colon (:) placed right before a loop:
outerLoop:
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (j == 2) {
break outerLoop; // Exits BOTH loops
}
}
}
How It Works
Think of labels like naming your loops. When you write break outerLoop;, you're saying "break out of the loop I named outerLoop" instead of just breaking the nearest one.
You can also use labels with continue:
searchLoop:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) {
continue searchLoop; // Skip to next i iteration
}
}
}
Why Use Labels?
Without labels, you'd need awkward boolean flags or complicated logic to break out of multiple nested loops. Labels make your intent crystal clear: "I want to exit this specific loop."
Key Takeaway: Labeled statements let you name loops with an identifier followed by a colon, allowing break and continue to target specific loops in nested structures, not just the innermost one.