Labeled Statement in Java: Labeled Break and Continue With Examples
A labeled statement in Java is a statement, usually a loop, given a name followed by a colon, such as search:. Labeled break and continue use that name to control an outer loop from inside an inner one. break search; exits the whole labeled loop, and continue search; jumps to its next iteration, all in one step.
Before you start: you need plain break and continue from Break and Continue in Java, and nested loops from For Loop in Java.
Key Takeaways
- Syntax:
labelName:placed directly before a loop; use it asbreak labelName;orcontinue labelName;. - A plain
breakorcontinueaffects only the innermost loop; a labeled one affects the named loop, at any depth. - A label does nothing on its own. It only matters when a
breakorcontinuenames it. - Java has no
goto. Labels can only exit or continue a statement that encloses the jump. - Labels cost nothing at runtime; the trade-off is readability. Often a method with
returnis clearer.
What Is a Labeled Statement in Java?
A label is a name you attach to a statement:
The label follows the same rules as a variable name: letters, digits, _ and $; it can’t start with a digit; and it can’t be a keyword. Labels live in their own namespace, so a label and a variable can even share a name (shown later). Choose a name that says what the loop does: pairSearch: tells the reader more than outer:.
You can put the label on the same line as the loop (pairSearch: for (...)) or on the line above. Both compile the same way.
Why Does a Plain break Fall Short in Nested Loops?
A plain break leaves only the innermost loop. In a search, that means the outer loop keeps going after the answer is found.
Here we look for two numbers that add up to 10:
Code (Java 21):
Output:
Pair: 8 + 2Comparisons: 9The first pair is 3 + 7, but the outer loop carried on, found 8 + 2, and overwrote the answer. It also did 9 comparisons instead of 4. That’s two bugs (a wrong result and wasted work) caused by one break that didn’t go far enough.
Labeled Break in Java: Exit Nested Loops in One Step
Label the outer loop and name it in the break:
Code (Java 21):
Output:
Pair: 3 + 7 (indexes 0 and 4)Comparisons: 4Dry Run of the Labeled Break
| Step | i | j | Pair checked | Sum = 10? | Action |
|---|---|---|---|---|---|
| 1 | 0 | 1 | 3 + 8 | no (11) | next j |
| 2 | 0 | 2 | 3 + 5 | no (8) | next j |
| 3 | 0 | 3 | 3 + 2 | no (5) | next j |
| 4 | 0 | 4 | 3 + 7 | yes | save indexes, break pairSearch → leave both loops |
The variables foundI and foundJ were declared before the labeled loop, so they’re still readable after it. Always store what you found before jumping out.
A plain break returns control to the outer loop, which keeps running. A labeled break jumps straight to the first statement after the labeled loop
Labeled Break With Three Nested Loops
The label works at any depth. Here, break lockSearch; leaves three loops at once:
Code (Java 21):
Output:
Code found: 247Attempts: 248The search tried codes 000 to 247 and stopped. Without the label, the outer loops would have kept counting toward 999.
Labeled Continue in Java: Skip to the Next Outer Iteration
A labeled continue abandons the rest of the current outer iteration, including any code after the inner loop, and starts the next one.
Here a student who fails any subject is skipped entirely:
Code (Java 21):
Output:
Asha: passed, total = 225Ravi: failed subject 2, skipped
Meena: passed, total = 181
For Ravi, continue studentLoop skipped his third subject and the “passed” line, then moved on to Meena.
What Goes Wrong With a Plain continue Here?
Swap in a plain continue, and it only skips the failing subject:
Code (Java 21):
Output:
Asha: passed, total = 225Ravi: passed, total = 145
Meena: passed, total = 181
Ravi is wrongly reported as passed, with his failing mark simply left out of the total. The program compiles and runs without errors, but the result is wrong. That makes this an easy bug to miss.
Labeled Continue With a While Loop
Labels work on while and do-while loops too. As always with while loops, update the counter before any continue:
Code (Java 21):
Output:
row 1, col 1row 2, col 1
row 3, col 1
done
If row++ came after the inner loop, continue rows would skip it, and the program would loop forever.
Does Java Have goto?
No. goto is a reserved word in Java that does nothing; trying to use it is a compile error:
Compiler output (Java 21):
GotoAttempt.java:5: error: illegal start of expressiongoto start;
^
GotoAttempt.java:5: error: not a statement
goto start;
^
2 errors
Labeled break and continue are deliberately limited. They can only leave, or move to the next pass of, a statement that encloses the jump. You can’t jump backward, sideways, or into another block. That limit is what makes them safe, unlike C’s goto.
Labeling a Block (Not Just a Loop)
Any statement can be labeled, including a plain { } block. A labeled break then exits the block early, which is a compact way to stop a sequence of checks.
Code (Java 21):
Output:
ravi_21 -> valida -> too short
meena! -> invalid characters
This is legal, but it’s rare in real code. A small method that returns the result is usually clearer. Only break works on a block label; continue needs a loop (see Mistake 3).
Alternatives: Flag Variable vs Method With return
Labels aren’t the only way to stop nested loops. Here are the two common alternatives, solving the same pair search.
Alternative 1: A Boolean Flag
Code (Java 21):
Output:
Pair: 3 + 7It works, but you need an extra variable plus a check in the outer condition, and the two must stay in sync.
Alternative 2: Extract a Method and return
Code (Java 21):
Output:
Pair: 3 + 7findPair(nums, 100) = nullreturn exits any number of nested loops, and the method name documents the intent. You’ll learn methods properly in the Methods lessons.
| Approach | Exits outer loop? | Extra state | Readability | Best when |
|---|---|---|---|---|
Plain break | No (innermost only) | None | Fine for one loop | Single loop |
| Flag variable | Yes, indirectly | A boolean | Verbose | Older code, simple cases |
Labeled break / continue | Yes, directly | None | Good if short | Short loops that update several local variables |
Method + return | Yes, all levels | None | Usually best | The search has one clear result to return |
Performance: all four compile to ordinary jumps, so labels have no extra runtime cost. Choose based on readability.
Label Scope and Naming Rules
- A label applies only to the statement directly after it, and is visible only inside that statement.
- You can’t reuse a label name for a statement nested inside another statement with the same label.
- You can reuse a name for two separate statements, one after the other.
- A label and a variable may share a name; they don’t clash.
Code (Java 21):
Output:
first scan: 0second scan: 0
second scan: 1
variable outer = 99
(The compact one-line if (…) break scan; is used here to keep the demo short; prefer braces in real code.)
Common Mistakes With Labeled Statements
Mistake 1: Using a Label Outside Its Statement
Compiler output (Java 21):
OutOfScope.java:8: error: undefined label: rowsbreak rows;
^
1 error
The rows loop has already ended, so its label no longer exists. A labeled jump must be inside the labeled statement.
Mistake 2: Reusing a Label on a Nested Loop
Compiler output (Java 21):
DuplicateLabel.java:5: error: label outer already in useouter:
^
1 error
Give each nested level its own name.
Mistake 3: continue With a Block Label
Compiler output (Java 21):
ContinueBlock.java:6: error: not a loop label: checkcontinue check;
^
1 error
continue means “next iteration”, and only loops have iterations. Use break check; for a block.
Mistake 4: Using a Plain continue When You Meant the Outer Loop
As the PlainContinueWrong example shows, this compiles and runs but gives a wrong result. Whenever an inner-loop condition should skip a whole outer item, use continue outerLabel;.
Mistake 5: Vague Label Names and Too Many Labels
outer: and loop1: say nothing about the loop’s purpose. If you need more than one or two labels in a method, extract a method instead.
Best Practices
- Reach for a label only when a plain
breakorcontinuecan’t do the job, which means nested loops. - Name labels after their purpose:
pairSearch:,studentLoop:,slotSearch:. - Declare result variables before the labeled loop and set them before jumping.
- Prefer extracting a method with
returnwhen the search has one clear result. - Keep labeled loops short enough that the label and its
breakfit on one screen. - In labeled while loops, update the loop state before any
continue label.
Real-World Example: Find the First Free Period in a Timetable
Code (Java 21):
Output:
First free slot: Wed, period 2This “search a grid, stop at the first match, remember the position” pattern is where labeled break is most often used: seat maps, game boards, matrices, and calendars. Wednesday’s second free period (period 4) was never checked.
Practice Problems
- Easy: In a 3×3 grid of numbers, find the first number greater than 50 and print its row and column, using a labeled
break. - Easy: Print the pairs
(i, j)fori, jin 1–4, but move to the nextias soon asj > i. Hint:continue outerLabel. - Medium: Given words in a 2D array (sentences × words), print only the sentences that contain no word longer than 6 letters. Hint: labeled
continueto skip a sentence. - Medium: Rewrite Practice Problem 1 as a method that returns the position (or
null) instead of using a label. - Medium: Find three numbers in an array that add up to a target using three nested loops, and stop all loops at the first match.
Try them in the ExamAdda online compiler.
Interview Questions on Labeled Break and Continue
1. What does a label do by itself?
Nothing. It only has an effect when a break label; or continue label; inside the labeled statement refers to it.
2. Difference between plain and labeled break?
A plain break exits only the innermost loop or switch; a labeled break exits the named enclosing statement, however deep the jump is nested.
3. Difference between labeled break and labeled continue?
A labeled break leaves the named loop completely; a labeled continue ends the current iteration of the named loop and starts its next one.
4. Does Java support goto?
No. goto is a reserved but unused keyword. Labeled break and continue can only exit or continue an enclosing statement.
5. Can you label a block or an if statement?
Yes, any statement can be labeled, and break label; exits it. continue label; works only with loops (“not a loop label” otherwise).
6. Do labeled jumps slow the program down?
No. They compile to ordinary jump instructions; the only cost is readability.
7. What alternatives exist to labeled break?
A boolean flag checked by the outer loop, or moving the loops into a method and using return, which is usually the clearest.
8. Can two loops use the same label name?
Yes if they’re one after the other; no if one is nested inside the other (“label … already in use”).
Article Summary
- A label (
name:) placed before a loop letsbreak name;andcontinue name;control that outer loop from an inner one. - A labeled
breakexits the named loop at any depth; a labeledcontinueskips to the named loop’s next iteration. - Java has no
goto; labeled jumps can only target statements that enclose them, and the compiler enforces label scope. - Labels have no runtime cost, but a method with
returnor a flag is often clearer. - Use descriptive label names, store results before jumping, and update while-loop counters before
continue.
Conclusion
Labeled break and continue solve one specific problem: controlling an outer loop from deep inside nested loops. Use them when that is exactly what you need, name the label after its purpose, and consider a method with return when the search has a single clear answer. Next in the series, you’ll study decision-making in If-Else Statements in Java. Meanwhile, sharpen your loop skills with ExamAdda practice questions.
Previous lesson: Break and Continue in Java
Next lesson: If-Else Statements in Java