Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 201 ยท Control Flow

break, continue and Labels

Control Java loops with break and continue, exit nested loops with labeled break, skip with labeled continue, return from loops, and avoid the classic traps.

A loop's condition decides when it normally ends, but real programs often need to change course in the middle of an iteration. Once a search finds what it's looking for, there's no point checking the remaining items. When a line of input is blank, you want to skip it and move on to the next one. Java gives you two jump statements for this: break leaves a loop immediately, and continue skips the rest of the current iteration.

On their own, both only affect the innermost loop. Labels let them target an outer loop, which is the clean way to escape nested loops in one step. This lesson covers all three, plus return inside loops and the traps that catch people (including one involving switch).

break: leave the loop now

break ends the innermost enclosing for, while, do-while or switch immediately. Execution continues with the first statement after that loop:

Java Stop at the first match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The loop stops at -999, so the readings after it (22 and 20) are never visited. A break usually sits inside an if; an unconditional break would end the loop on its first iteration, and the compiler reports any statement right after it in the same block as an unreachable statement.

break is also how you leave a deliberate while (true) loop, as you saw in while and do-while Loops. And it's what stops a classic switch from falling through (see switch Statements and Expressions), which leads to the first trap.

Trap: break inside a switch inside a loop

A break belongs to the innermost loop or switch. Inside a switch that sits in a loop, break leaves only the switch, not the loop:

Java break leaves the switch, not the loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

After quit, the program happily reads the next line: the break only ended the switch. Only exit, which uses return, really stops. The same rule applies to arrow-style switch statements: a break inside a case ... -> { } block leaves the switch. To leave the loop from inside a switch, use a labeled break (below), return, or a flag that the loop condition checks.

continue: skip to the next iteration

continue skips the rest of the current iteration's body and jumps to the loop's next step:

  • In a while or do-while loop, it jumps to the condition check.
  • In a classic for loop, it jumps to the update (i++), then the condition.
  • In a for-each loop, it moves on to the next element.

continue is ideal for filtering: handle the "skip this one" cases at the top of the body, and keep the main work unindented below.

Java Skipping lines with continue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Without continue, the same logic needs nested if/else blocks, with the real work three levels deep. It's the loop version of the guard clauses from if, else if and else.

Trap: continue before the update in a while loop

In a for loop the update always runs, because it lives in the header. In a while loop the update is just a statement in the body, and continue can jump right over it:

Java
int i = 0;
while (i < 10) {
    if (i % 2 == 0) {
        continue;      // i++ below is skipped: i stays 0 forever!
    }
    IO.println(i);
    i++;
}

This loops forever at i == 0. Move the update before the continue (or to the top of the body), or use a for loop, which can't have this bug:

Java continue in for versus while

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Both loops print the same odd numbers, but they get there differently: the while version increments before testing, so it examines 1 to 10 instead of 0 to 9. Here that happens not to matter, but moving an update always changes which values a loop sees, so re-check the first and last values whenever you restructure a loop.

Labeled break: escaping nested loops

A plain break inside an inner loop ends only the inner loop; the outer loop carries on. To stop both, put a label (an identifier followed by a colon) in front of the outer loop and name it in the break:

Java Labeled break: search a grid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output shows the search stops at the first free seat, row 1, seat 2: the rest of row 1 and all of row 2 are never checked. With an unlabeled break, the outer loop would continue into row 2 and keep checking seats. (char[][] is a two-dimensional array; Multidimensional Arrays covers them.)

Labels follow a few rules:

  • A label goes directly before the statement it names, conventionally on its own line. Lowercase names like outer, search or rows are the norm.
  • break label; can only target a label on a statement that encloses it. You can't jump forward, backward or into another loop. Java has no goto (the word is reserved but unused).
  • break with a label works on any labeled block, not just loops, though using it outside loops is rare and usually a sign the code should be a method.

Labeled continue

continue label; ends the current iteration of the labeled loop, abandoning any inner loops on the way. It reads as "this outer item is done, move on to the next one":

Java Labeled continue: list primes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

As soon as a divisor turns up, there's no need to test the rest, and no need for a boolean isPrime flag either: primes.add(n) only runs when the inner loop finished without jumping.

return: leaving the loop and the method

Inside a method, return ends the loop and the whole method in one step, from any depth of nesting. When the purpose of a loop is to find something, putting it in its own method and returning the answer is often the cleanest design of all:

Java return from inside nested loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Compared with a labeled break, the method version has a name that explains the loop, needs no "found" variables, and is easy to test on its own. Many teams prefer it, and use labels only when the loop can't easily move into a method. Returning null for "not found" is simple but easy to forget to check; Optional shows a safer way to return "maybe a value".

If a loop runs inside a try block with a finally, the finally block still runs when you leave with break, continue or return. You'll see why that matters in Exceptions and try-catch.

Choosing the right tool

You want to... Use
Stop the loop once you've found or decided something break
Skip this item and go on with the next continue
Stop an outer loop from inside an inner loop break label; or a method with return
Move on to the next item of an outer loop continue label;
Exit a loop from inside a switch return, a labeled break, or a flag
Check whether any item matches Often a stream: list.stream().anyMatch(...)

Jump statements are tools, not goals. A loop with one clear break or a couple of continue guards is easy to read; a loop with five exits scattered through the body is not. If you need many, the loop is probably doing too much, and splitting it into methods will help.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? for (int i = 1; i <= 5; i++) { if (i == 3) { break; } IO.print(i + " "); }

    The loop prints 1 and 2. When i is 3, break ends the loop before the print runs, so 3, 4 and 5 never print.
  2. 2. What does this print? for (int i = 1; i <= 5; i++) { if (i == 3) { continue; } IO.print(i + " "); }

    continue skips the rest of the body only for i == 3. The update i++ still runs, and the loop goes on with 4 and 5.
  3. 3. Inside a classic switch that is inside a while (true) loop, what does a plain break; do?

    break targets the innermost enclosing loop or switch, which is the switch. Use a labeled break, return or a flag to end the loop.
  4. 4. How many times does checked++ run? outer: for (int a = 0; a < 3; a++) { for (int b = 0; b < 3; b++) { checked++; if (b == 1) { continue outer; } } }

    For each of the 3 values of a, the inner loop runs for b = 0 and b = 1, then continue outer moves to the next a. That's 2 x 3 = 6.
  5. 5. Why can this loop run forever? int i = 0; while (i < 5) { if (i == 2) { continue; } i++; }

    In a while loop, continue jumps straight to the condition. The update is in the body after the continue, so i stays 2 forever. A for loop keeps its update in the header, so it doesn't have this problem.

Summary

  • break ends the innermost loop or switch immediately; continue skips to the next iteration (the update in a for, the condition in a while).
  • Inside a switch within a loop, a plain break leaves only the switch.
  • In while loops, make sure continue can't skip the update, or the loop may never end.
  • Labels (outer:) let break outer; exit an enclosing loop and continue outer; move to its next iteration; Java has no goto.
  • return leaves every loop and the method at once; moving a search loop into its own method is often the clearest design.
  • Keep jumps few and obvious; many exits are a sign the loop should be split up.

Next: Arrays, where you'll store many values in one variable and put your new loop skills to work.