Java break, continue, Labels, return and Unreachable Code (OCP 21)
The OCP Java 21 rules for branching: labels on statements, break and continue with and without a label, break inside a switch inside a loop, return as a way out of nested loops, and the compiler's unreachable-code and missing-return checks.
kvi5hnuCode Sprout team member8 min readOn this page
Loops normally end when their condition becomes false. Branching statements change that: break leaves a statement early, continue skips to the next iteration, and return leaves the whole method. With nested loops, a label says which loop you mean. Exam questions in this area are usually long nested loops with a single break or continue in the middle, or code the compiler refuses because a statement can't be reached. This article covers both.
Labels
A label is an identifier followed by a colon, placed in front of a statement:
OUTER:
for (int i = 0; i < 3; i++) {
INNER: for (int j = 0; j < 3; j++) {
// …
}
}
- Labels follow identifier rules. By convention they're written in upper snake case, like constants.
- Any statement can be labeled: loops,
switch,if, a block{ … }, evenx++;. It's only useful on statements thatbreakorcontinuecan target. - Labels have their own namespace, so a label and a variable can share a name. A label can be reused for statements that come one after another, but not for a statement nested inside another statement with the same label ("label L already in use").
- A label can be used only from inside the statement it labels.
break OUTfrom a later, separate loop fails with "undefined label: OUT".
break
break ends the innermost enclosing while, do/while, for, for-each or switch statement, and execution continues with the statement after it. break LABEL ends the labeled statement instead, however deeply it's nested.

Look at how three versions of the same search give three different answers on {{4, 7}, {9, 3}, {3, 3}} when they look for 3:
| Version | What happens | Result |
|---|---|---|
break SEARCH; (labeled outer loop) | Stops at the first match anywhere | (1,1) |
plain break; | Stops the inner loop only; the outer loop keeps going, so later rows overwrite the result | (2,0), the first match in the last row that has one |
no break | Every match overwrites the previous one | (2,1), the last match |
Rules:
- A plain
breakoutside a loop orswitchfails with "break outside switch or loop". - A labeled
breakcan leave any labeled statement, including a plain block:
CHECK: {
if (stock == 0) break CHECK; // skips the rest of the block
ship();
}
continue
continue ends the current iteration and goes to the loop's next step: the condition for while, the condition for do/while, the update and then the condition for for, and the next element for for-each. continue LABEL does the same for the labeled loop, abandoning any inner loops on the way.
SHELF:
for (char shelf = 'a'; shelf <= 'c'; shelf++) {
for (int box = 1; box <= 3; box++) {
if (shelf == 'b' || box == 2) continue SHELF;
System.out.print(shelf + "" + box + " ");
}
}
// a1 c1 (with a plain continue: a1 a3 c1 c3)
Rules:
continueworks only in loops. Outside one, it fails with "continue outside of loop".continue LABELmust name a loop. Using it with a labeled block orswitchfails with "not a loop label".- In a
do/while,continuejumps to the condition, so the condition still runs.do { continue; } while (i++ < 3);ends normally.
break and continue inside a switch in a loop
This combination appears on the exam all the time:
for (int i = 0; i < 5; i++) {
switch (i) {
case 1: continue; // continues the LOOP
case 3: break; // leaves only the SWITCH
default: System.out.print(i);
}
System.out.print(".");
}
// 0.2..4.
- A
breakin a switch statement leaves the switch, not the loop. To leave the loop, usebreakwith a label on the loop. - A
continuein a switch statement applies to the enclosing loop.switchhas no "next iteration" of its own. - A switch expression can't be jumped out of.
breakorcontinuethat would leave one fails with "attempt to break out of a switch expression" or "attempt to continue out of a switch expression". Areturninside one fails too (article 12). Useyieldto give it a value.
| Statement | Labels | break | continue | yield | when guards |
|---|---|---|---|---|---|
while, do/while, for, for-each | Yes | Yes | Yes | No | No |
switch statement | Yes | Yes | Only to an enclosing loop | No | Yes |
switch expression | No (it's an expression) | No | No | Yes | Yes |
Block { }, if | Yes | Only a labeled break | No | No | No |
return as an exit
return leaves the method straight away, however many loops are open. Moving a nested search into its own method often replaces a labeled break with something easier to read:
static int[] find(int[][] grid, int wanted) {
for (int r = 0; r < grid.length; r++)
for (int c = 0; c < grid[r].length; c++)
if (grid[r][c] == wanted) return new int[] {r, c};
return null; // or Optional, or an empty array
}
Both styles are on the exam. In real code, prefer small methods with return to labels. Labels are rare in modern Java.
Unreachable code
The compiler rejects any statement that it can prove will never run, with "unreachable statement". This is a compile-time analysis based on the code's structure. It doesn't matter how often the code would actually run.
Directly after a jump. Nothing can follow break, continue, return or throw in the same block, not even an empty statement ;:
while (n < 10) {
n++;
if (n > 100) {
break;
n++; // DOES NOT COMPILE
}
}
switch (hour) {
case 1: return; hour++; // DOES NOT COMPILE
case 2:
}
After a loop that can never finish. A loop whose condition is the constant true (or that leaves out the condition) completes normally only if a break targets it. Otherwise the next statement is unreachable:
while (true) { } System.out.print(1); // DOES NOT COMPILE
for (;;) { continue; } System.out.print(1); // DOES NOT COMPILE
while (true) { if (done) break; } System.out.print(1); // compiles
OUT: while (true) { while (true) { break OUT; } } System.out.print(1); // compiles
OUT: while (true) { while (true) { break; } } System.out.print(1); // DOES NOT COMPILE
In the last line, the plain break only ends the inner loop. Nothing ever ends the outer one.
Inside a loop that can never start. A body behind a constant false condition is unreachable: while (false) { … } and for (;false;) { … } fail, while do { … } while (false); compiles (article 14).
The if exception. if (false) { … } and code after if (true) return; both compile. The language allows this on purpose, so that if (DEBUG) with a static final boolean can switch code on and off.
Missing return and endless loops
The same analysis decides whether a non-void method needs a return at the end:
int spin() {
while (true) { } // compiles: the end of the method is unreachable
}
int spinOnce() {
for (;;) { break; } // DOES NOT COMPILE: missing return statement
}
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Labels,
break,continueand the unreachable-code rules date from Java 1.0. The only newer twist isyield, which leaves aswitchexpression (article 12).
Exam traps from this article
A complete example
import java.util.Arrays;
public class Solution {
static final int[][] SEATS = {{4, 7}, {9, 3}, {3, 3}};
// Three ways to stop a search, with three different answers
static String findWithLabel(int wanted) {
int row = -1, col = -1;
SEARCH:
for (int r = 0; r < SEATS.length; r++) {
for (int c = 0; c < SEATS[r].length; c++) {
if (SEATS[r][c] == wanted) {
row = r;
col = c;
break SEARCH; // leaves both loops
}
}
}
return "(" + row + "," + col + ")";
}
static String findWithPlainBreak(int wanted) {
int row = -1, col = -1;
for (int r = 0; r < SEATS.length; r++) {
for (int c = 0; c < SEATS[r].length; c++) {
if (SEATS[r][c] == wanted) {
row = r;
col = c;
break; // leaves only the inner loop
}
}
}
return "(" + row + "," + col + ")";
}
static String findWithoutBreak(int wanted) {
int row = -1, col = -1;
for (int r = 0; r < SEATS.length; r++) {
for (int c = 0; c < SEATS[r].length; c++) {
if (SEATS[r][c] == wanted) {
row = r;
col = c;
}
}
}
return "(" + row + "," + col + ")";
}
// return leaves the loops and the method in one step
static int[] findWithReturn(int wanted) {
for (int r = 0; r < SEATS.length; r++) {
for (int c = 0; c < SEATS[r].length; c++) {
if (SEATS[r][c] == wanted) {
return new int[] {r, c};
}
}
}
return null;
}
public static void main(String[] args) {
System.out.println("-- break --");
System.out.println("labeled break: " + findWithLabel(3));
System.out.println("plain break: " + findWithPlainBreak(3));
System.out.println("no break: " + findWithoutBreak(3));
System.out.println("return: " + Arrays.toString(findWithReturn(3)));
System.out.println("missing: " + Arrays.toString(findWithReturn(8)));
System.out.println("-- continue with and without a label --");
StringBuilder labeled = new StringBuilder();
SHELF:
for (char shelf = 'a'; shelf <= 'c'; shelf++) {
for (int box = 1; box <= 3; box++) {
if (shelf == 'b' || box == 2) continue SHELF;
labeled.append(shelf).append(box).append(' ');
}
}
System.out.println("continue SHELF: " + labeled.toString().trim());
StringBuilder plain = new StringBuilder();
for (char shelf = 'a'; shelf <= 'c'; shelf++) {
for (int box = 1; box <= 3; box++) {
if (shelf == 'b' || box == 2) continue;
plain.append(shelf).append(box).append(' ');
}
}
System.out.println("continue: " + plain.toString().trim());
System.out.println("-- break and continue inside a switch in a loop --");
StringBuilder trace = new StringBuilder();
for (int i = 0; i < 5; i++) {
switch (i) {
case 1:
continue; // next loop iteration
case 3:
break; // leaves only the switch
default:
trace.append(i);
}
trace.append('.');
}
System.out.println(trace);
System.out.println("-- a labeled block --");
int stock = 0;
CHECK: {
if (stock == 0) {
System.out.println("out of stock, skipping the rest of the block");
break CHECK;
}
System.out.println("in stock");
}
System.out.println("after the block");
}
}
Output:
-- break --
labeled break: (1,1)
plain break: (2,0)
no break: (2,1)
return: [1, 1]
missing: null
-- continue with and without a label --
continue SHELF: a1 c1
continue: a1 a3 c1 c3
-- break and continue inside a switch in a loop --
0.2..4.
-- a labeled block --
out of stock, skipping the rest of the block
after the block
Points to notice:
- The three search methods differ only in their
break, and they give three different positions. findWithReturnneeds no label and no position variables.nullsignals "not found".continue SHELFabandons the whole shelf at the first skip, while a plaincontinueskips only that box.- In the switch,
continueskips thetrace.append('.')after the switch, butbreakdoesn't. break CHECKleaves a labeled block. That's the only way to usebreakoutside a loop or switch.
Common questions
Are labels considered bad style?
They're legal and occasionally the clearest choice, for example to leave a nested search once without a flag variable. Most style guides prefer extracting a method and using return. Expect labels on the exam more often than in code reviews.
Can I goto a label?
No. goto is a reserved keyword in Java that does nothing. Labels can only be targets for break and continue, and those jump forward, out of the labeled statement, never backward to an arbitrary line.
Why does if (false) compile when while (false) doesn't?
The language specification exempts if on purpose, so that constant flags such as static final boolean DEBUG = false; can switch code on and off, the way conditional compilation works in C.
Does throw count for unreachable code too?
Yes. A statement directly after throw in the same block is unreachable. Exceptions are covered in Chapter 11.
What about code after System.exit(0)?
It compiles. System.exit is an ordinary method call, so the compiler doesn't know it never returns.
Summary
- Labels name statements.
break LABELleaves any enclosing labeled statement.continue LABELmust name an enclosing loop. - A plain
breakends the innermost loop or switch statement. A plaincontinuegoes to the innermost loop's next iteration, even from inside aswitch. - Switch expressions can't be left with
break,continueorreturn. Useyield. returnexits every loop at once and is usually clearer than labels.- A statement after
break,continue,returnorthrowin the same block, after an endless loop with nobreak, or insidewhile (false)is an unreachable-statement error.ifis exempt. - A method that ends in an endless loop needs no final
return.
Practice quiz
Test yourself with the break, continue and unreachable code quiz: 10 exam-style questions with explanations.
Finished Chapter 3? Take the Chapter 3 review: Making Decisions: 20 mixed questions covering articles 11 to 15.
Previous: Java while, do/while, for and for-each Loops (OCP 21)
Next: Java Strings: Creation, Concatenation and Immutability (OCP 21)
Related reading
- Java while, do/while, for and for-each Loops (OCP 21)
- Java Pattern Matching for switch: Type Patterns, when Guards, null and Record Patterns (OCP 21)
- Java switch Statements and switch Expressions: case Values, yield and Exhaustiveness (OCP 21)
- Java if/else, Pattern Matching for instanceof and Flow Scoping (OCP 21)
- Java Equality, Relational, Logical and Ternary Operators (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.