The Analogy: The Reject Chute And The Stop Cord
An inspector stands beside a sorting belt as parcels come past. Two things are within reach. At waist height there is a lever that swings a flap and drops the parcel in front of him into the reject chute; the belt does not slow down, the next parcel arrives on schedule, and his shift carries on. Above his head there is a cord, and pulling it stops the belt.
Those are not two strengths of the same control. The chute is a decision about one parcel. The cord is a decision about the whole run, and everything still upstream of him stays upstream. A parcel down the chute is still a parcel he handled -- it goes on the tally as inspected and rejected. A pulled cord means the parcels behind it were never looked at, and the only honest way to close the shift is to say how many that was.
Both controls are wired to the belt he is standing at and to nothing else. If a second, shorter belt feeds parcels onto his line, the cord above his station does not stop it; his belt halts and the feeder keeps pushing. To stop the whole line he needs the master button at the end of the hall, and that button is wired to a named line rather than to whichever belt happens to be nearest. A label on a Java loop is that name, and break label is that button.
The failures are all about bookkeeping. A cord pulled for a condition that occurs on nearly every parcel means the line never runs, and the log says "stopped" without saying that it stopped on parcel two of eight thousand. A chute lever pulled before the tally clicks means the rejects leave the building without ever appearing in a count, so eight thousand parcels went in, seven thousand nine hundred came out, and nothing in the paperwork accounts for the difference. And an inspector who pulls the cord and then signs the sheet "all parcels inspected" has produced the worst outcome available: a partial run that reads as a complete one.
Syntax or Core Structure
break leaves the loop. continue abandons the rest of this pass and goes to the next one. A label lets either of them act on an outer loop instead of the innermost one.
public class Belt {
public static void main(String[] args) {
int[] parcels = { 3, 0, 7, -1, 4 };
int inspected = 0;
int passed = 0;
for (int i = 0; i < parcels.length; i++) {
inspected++;
if (parcels[i] == 0) {
continue;
}
if (parcels[i] < 0) {
break;
}
passed++;
}
System.out.println("inspected " + inspected);
System.out.println("passed " + passed);
outer:
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
if (row * col == 4) {
System.out.println("found " + row + "x" + col);
break outer;
}
}
}
int checked = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) {
break;
}
checked++;
}
}
System.out.println("checked " + checked);
}
}
Output:
inspected 4
passed 2
found 2x2
checked 3
The first loop saw four of five parcels: the zero was skipped but still counted as inspected, and the negative one stopped the belt before the fifth parcel existed as far as this program is concerned. The third loop is the proof that an unlabelled break only ever leaves one loop: three outer passes each managed exactly one inner pass before breaking, so checked is 3 and not 1. A label is attached to a statement, and break outer leaves that whole statement, which is why the middle loop stops at the first row-times-column that makes 4 instead of finishing the row.
Technical Depth: Exactly Where Control Lands, And What These Two Statements Cannot Reach
The landing points
| Statement | In a for loop | In a while loop | In a do-while | In a switch |
|---|---|---|---|---|
break | the line after the loop | the line after the loop | the line after the loop | the line after the switch |
continue | the advance clause | the condition | the condition | continues the enclosing loop, if there is one |
The row that catches people is continue in a while loop: it goes to the condition, not to the bottom of the body, so any advance written at the bottom of the body is skipped and the loop sticks. In a for loop the advance clause still runs, which is why the same code is safe there and not here.
A break inside a switch is a different statement with the same spelling
int[] codes = { 1, 2, 9, 3 };
int handled = 0;
int unknown = 0;
int logged = 0;
for (int i = 0; i < codes.length; i++) {
switch (codes[i]) {
case 1:
case 2:
handled++;
break;
case 3:
handled++;
break;
default:
unknown++;
continue;
}
logged++;
}
System.out.println("handled " + handled);
System.out.println("unknown " + unknown);
System.out.println("logged " + logged);
Output:
handled 3
unknown 1
logged 3
Three of the four codes reached logged++. The break statements did exactly nothing to the loop -- they ended the switch, control fell out of the bottom of it, and the next line of the loop body ran as normal. Only the continue in the default arm reached past the switch and skipped the rest of the pass, which is why code 9 was counted as unknown and never logged.
This is the single most common misreading of break in Java. If you want to leave a loop from inside a switch that is inside that loop, an unlabelled break cannot do it; you need a label on the loop, or a return, or a flag.
Labelled break and labelled continue do quite different things
int[][] grid = {
{ 1, 2, 3 },
{ 4, -1, 6 },
{ 7, 8, 9 }
};
int stopped = 0;
search:
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
if (grid[r][c] < 0) {
break search;
}
stopped += grid[r][c];
}
}
System.out.println("stopped " + stopped);
int skipped = 0;
rows:
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
if (grid[r][c] < 0) {
continue rows;
}
skipped += grid[r][c];
}
}
System.out.println("skipped " + skipped);
Output:
stopped 10
skipped 34
break search abandons both loops, so the total is 1 + 2 + 3 + 4 and nothing else. continue rows abandons only the current row and advances the outer loop, so row 2 contributes its leading 4 and then gives up on the 6, and row 3 is added in full: 6 + 4 + 24.
Look closely at what continue rows did not undo. The 4 from the bad row is still in the total. A labelled continue abandons a half-finished piece of work and keeps whatever that work had already written -- variables updated, rows inserted, files appended. If a row must be all-or-nothing, accumulate into a local and only merge it into the running total once the row has finished cleanly.
What neither statement can do
| Goal | Right tool | Wrong tool |
|---|---|---|
| stop this loop | break | a flag set in the body and retested in the condition |
| stop every enclosing loop | labelled break | one flag rechecked at the top of each level |
| leave the whole method | return | break plus a result variable |
| skip the rest of this pass | continue | wrapping the entire body in one large if |
| jump forward to a later point | nothing; restructure the code | goto, which Java reserves as a keyword and does not implement |
Neither statement can leave a method, carry a value, or jump to a label that is not on an enclosing statement -- a label must sit on a statement that contains the jump. And code placed after an unconditional break or continue in the same block is unreachable, which is a compile error rather than a warning; the usual cause is a logging line that somebody moved one line too far down.
Real World Example: A Batch Importer That Skips Bad Rows And Stops On A Bad File
Two kinds of problem turn up in an import, and they need opposite answers. A row that cannot be parsed is that row's problem: note it and move on. A marker saying the file itself is truncated is the whole batch's problem: stop, because importing the readable part as if it were complete is worse than importing nothing.
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class Importer {
private static final String[] LINES = {
"ok,alpha,120",
"",
"ok,beta,x9",
"ok,gamma,340",
"#truncated",
"ok,delta,50"
};
public static void main(String[] args) {
List<String> accepted = new ArrayList<String>();
int total = 0;
int read = 0;
int blank = 0;
int malformed = 0;
boolean aborted = false;
for (int i = 0; i < LINES.length; i++) {
String line = LINES[i];
read++;
if (line.isEmpty()) {
blank++;
continue;
}
if (line.startsWith("#")) {
aborted = true;
break;
}
String[] cell = line.split(",");
int amount;
try {
amount = Integer.parseInt(cell[2]);
} catch (NumberFormatException e) {
malformed++;
continue;
}
accepted.add(cell[1]);
total += amount;
System.out.println(String.format(Locale.ROOT,
"line %d name %-6s amount %4d", i + 1, cell[1], amount));
}
System.out.println("read " + read);
System.out.println("accepted " + accepted.size());
System.out.println("blank " + blank);
System.out.println("malformed " + malformed);
System.out.println("total " + total);
System.out.println("aborted " + aborted);
System.out.println("unread " + (LINES.length - read));
}
}
Output:
line 1 name alpha amount 120
line 4 name gamma amount 340
read 5
accepted 2
blank 1
malformed 1
total 460
aborted true
unread 1
The two statements in this loop encode two different policies, and the choice between them is a data-integrity decision rather than a style preference. A blank line and an unparseable amount are row-scoped faults: the file is still trustworthy, so skip the row, record that you skipped it, and keep going. The # marker says the file is not trustworthy, and continuing past it would produce a partial batch wearing the shape of a complete one. continue and break are how those two policies get written down.
Every continue in this loop increments its counter before it jumps, and that ordering is what makes skipping safe. The numbers reconcile: five lines read, of which two accepted, one blank, one malformed, and one the abort marker itself. Move blank++ below the continue and it becomes unreachable code that will not compile; move read++ to the bottom of the body and it compiles perfectly and quietly stops counting the skipped lines, so the run reports five lines in and two out with nothing accounting for the rest. Count first, jump second.
The break sets aborted before it leaves, and unread says how much of the file was never looked at. A break that records nothing turns a stopped import into an apparently successful short one, which is the same failure as an unreported loop guard: the loop can end for two reasons and the caller cannot tell them apart. If a loop has more than one exit, the exit taken is part of its result.
The honest limits, and this program has a real one. total and accepted still hold data after the abort -- the code has decided the file is untrustworthy and is nonetheless sitting on 460 pence and two names that a caller is free to commit. A boolean beside the data is not protection, because nothing forces anyone to read it; the abort should discard, or the method should return a type that cannot be unpacked without answering the question. Beyond that: split(",") does no quoting, so a name containing a comma shifts the amount into the wrong column and a two-column line makes cell[2] throw an ArrayIndexOutOfBoundsException that nothing here catches, meaning a malformed row can still kill the import rather than be counted as malformed. The truncation check only fires on an explicit marker, so a file that simply ends early imports clean, short and wrong. And the reported line numbers rely on i + 1 being the file line, which is true only because there is no header row; add one and every number in the output is off by one.
Common Mistakes
- Using
continuein awhileloop that advances at the bottom of the body.continuejumps to the condition, so the increment never runs and the loop sticks on the value that triggered the skip. Advance before thecontinueis reachable, or use aforloop, whose advance clause still runs.
- Expecting
breakinside aswitchto leave the surrounding loop. It ends theswitchand control drops to the next statement in the loop body. Use a label on the loop, areturn, or acontinueif skipping the rest of the pass is what you meant.
- Expecting an unlabelled
breakto leave nested loops. It leaves the innermost one only, so the outer loop starts a fresh inner loop on its next pass. Label the loop you actually want to leave.
- Reading
continue labelas "restart that loop's body". It advances the labelled loop, abandoning everything inside it -- and it does not undo the part of that pass that already ran. Accumulate into a local and merge on success if the pass must be all-or-nothing.
- Jumping without recording why. A
breakthat leaves no flag, and no count of what was not processed, converts a truncated run into a silently successful one. The exit reason belongs in the result.
- Incrementing counters after the jump instead of before it. For
continuethe counter is simply skipped; the numbers stop reconciling and no error is raised. For an unconditional jump the compiler catches it as unreachable code, which is the lucky case.
- Using
breakplus a result variable when the loop is the whole method.return ifrom inside the loop is shorter, needs no sentinel, and cannot leave a stale flag behind for the next reader to misinterpret.
- Writing
continueas the last statement of a loop body. It does nothing at all, and its presence tells the next reader that the author believed it did something -- usually that it would skip anelsebranch that is not there.
- Putting the jump conditions at the bottom of a long body.
breakandcontinueburied under thirty lines of work are invisible, and by the time they fire the body has already done most of what the jump was meant to prevent. They belong at the top, as guard clauses.
Best Practices
- Update every counter and every reason before you jump.
blank++; continue;reconciles;continue; blank++;will not compile, and the version that moves the counter somewhere else entirely compiles and lies.
- Report which exit the loop took. A loop with a
breakhas at least two endings, and a caller holding only the collected data cannot tell "finished" from "gave up". Return the flag, the count of unprocessed items, or both.
- Prefer
returnwhen the loop is the entire method. Searching, matching and first-hit lookups read better asreturn ithan asbreakwith an index variable that has to be interpreted afterwards.
- Label a loop only when a nested jump genuinely needs it, and name the label after the loop's job.
rows:andsearch:tell a reader what is being abandoned;outer:andloop1:tell them nothing and stop meaning anything once a third level appears.
- Keep jump conditions at the top of the body as guard clauses. Two or three early
continues read far better than oneifwrapping thirty lines, and they put the skip rules where they can be checked against the counters.
- Make an all-or-nothing pass all-or-nothing. If a
continuecan fire halfway through a pass, build the pass's result in local variables and publish it only at the end, so an abandoned pass leaves nothing behind.
- Distinguish item-level faults from batch-level faults in the code's vocabulary. Name the counters and the flags after that distinction.
continueis the item policy andbreakis the batch policy, and confusing them is how partial data gets committed.
- Never leave a bare
breakin aswitchwhere fall-through was intended. If an arm is meant to fall into the next one, say so in a comment; a reader cannot otherwise tell a deliberate omission from a missing statement.
Practice Exercises
- The Reconciliation. Add a final line to
Importerthat assertsread == accepted.size() + blank + malformed + (aborted ? 1 : 0)and prints whether it held. Then break it in two ways: moveread++to the bottom of the loop body, and add a fourth skip rule -- reject any line whose name is shorter than three characters -- without adding a counter for it. Run all three versions and show which numbers stop adding up in each case.
- The Abort That Discards. Restructure the importer so that an abort cannot leak partial data. Extract the loop into a method returning a small class holding
names,total,abortedandunread, and make the abort path return an instance whosenamesis empty and whosetotalis zero while still reportingunread. Then explain in two sentences why the flag alone was insufficient in the original.
- The Labelled Grid. Take the
gridblock and add a third traversal in which the label sits on the inner loop -- call itcells:-- and the jump iscontinue cells. Predict its total before running it, and say which of the two existing traversals it matches and why. Then rewrite thecontinue rowsversion so that a row containing a negative number contributes nothing at all, and show that the total drops from 34 to 30.