Skip to content
Ameen Abozaid
PublishedBEG-013-L04

break, continue, and loop control

  • Lesson 4 of 7
  • 10 min read
  • Beginner
On This Lesson 11 topics

Lesson Overview

So far a loop ends only when its condition becomes false. Sometimes you want more control. You have found what you were looking for and there is no point running the remaining laps. Or one lap is not worth finishing and you want to jump to the next. Java gives you two statements for that: break and continue.

On the track: break is leaving the track now, mid-lap, and walking home. continue is skipping the rest of this lap and heading straight to the start of the next one, with the counter still moving on.

Why this matters: searching, skipping bad records, and stopping at a sentinel value ("stop when you see 0") are everyday backend patterns. Used well, these two statements make loops shorter. Used badly, they make logic tangled, so this lesson also teaches when not to use them.

This lesson builds on BEG-013-L01 to L03 and on if from BEG-012.

Learning Objectives

By the end of this lesson you will be able to:

  • Use break to leave a loop immediately.
  • Use continue to skip the rest of the current iteration.
  • Say what happens to the update in a for loop when continue runs.
  • Say which loop a break or continue affects in nested loops.
  • Use while (true) with break for a loop that stops in the middle.
  • Decide when a plain condition is clearer than break or continue.

Written Explanation

break: leave the loop

break ends the innermost loop (or switch) that contains it. Execution continues with the first statement after the loop. You already met break in BEG-012-L03 inside switch; in a loop it has the same meaning: jump out.

java
for (int i = 1; i <= 10; i++) {
    if (i == 4) break;
    System.out.println(i);
}
System.out.println("after");

This prints 1, 2, 3, then after. When i is 4, break ends the loop; the println(i) for 4 never runs.

continue: skip to the next iteration

continue ends the current iteration only. The loop does not stop: control goes to the next step of the loop.

  • In a for loop it goes to the update (i++), then the condition check.
  • In a while or do-while it goes straight to the condition check.
java
for (int i = 1; i <= 5; i++) {
    if (i == 3) continue;
    System.out.println(i);
}

This prints 1, 2, 4, 5. The Java Tutorials describe continue as skipping the current iteration and moving to the controlling expression of the loop.

The difference is worth burning into memory:

StatementEffect on the loopRest of the body
breakEnds itSkipped
continueKeeps goingSkipped for this iteration only

Which loop is affected

In nested loops (more in L05), an unlabeled break or continue acts on the innermost loop only. The outer loop carries on. Java also has labeled breaks that can leave an outer loop; they are rarely needed and we do not use them in this course.

The loop that stops in the middle

Sometimes the natural stopping point is neither at the top nor at the bottom of the body, but halfway through: read a value, and if it is the stop signal, quit; otherwise use it. A while (true) plus break expresses this directly:

java
while (true) {
    int amount = scanner.nextInt();
    if (amount == 0) break;      // sentinel: 0 ends the input
    total += amount;
}

A value like 0 here is called a sentinel: a special value that means "stop". The condition true never becomes false, so the break is the only way out. Always check that a break can actually be reached.

Do not change the loop variable in the body

You may be tempted to write i++ or i = 10 inside a for body to skip or to end. Do not: it makes the iteration count hard to predict. Use continue to skip and break to end; both say what you mean.

When not to use them

break and continue are good for clear special cases at the top of the body ("skip invalid", "stop when found"). They are bad when the body has several of them scattered about, because the reader must hunt for every exit. If you have three breaks and two continues, rewrite the condition or move the logic into a method.

Also, the compiler knows that code after an unconditional break or an endless loop cannot run, and it reports an error. We will see that in L06.

Examples

Example 1: skip evens, stop after 7 (simple)

java
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) continue;   // skip evens
    if (i > 7) break;           // stop after 7
    System.out.println(i);
}

Output:

text
1
3
5
7

Trace: i = 2, 4, 6 hit continue. i = 9 is odd, so it passes the first if, and then 9 > 7 triggers break. Nothing is printed for 9, 10.

Example 2: find the first multiple (practical)

Find the first multiple of 7 above 50:

java
int n = 50;
while (true) {
    n++;
    if (n % 7 == 0) break;
}
System.out.println("First multiple of 7 above 50: " + n);

Output:

text
First multiple of 7 above 50: 56

The pattern "search, and stop when found" is the most common use of break. The % remainder operator is from BEG-010-L01. The same search without break would need the condition n % 7 != 0 in the loop header, which is perhaps even clearer; you will often have this choice.

Example 3: sum payments until a sentinel (realistic)

A cash desk reads amounts one per line. A negative number is a mistake that should be ignored, and 0 means "end of the batch":

java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int total = 0;
        while (true) {
            int amount = scanner.nextInt();
            if (amount == 0) break;
            if (amount < 0) continue;
            total += amount;
        }
        System.out.println("Total " + total);
    }
}

With the inputs 5, -3, 7, 0 (one per line), the output is:

text
Total 12

-3 is skipped by continue and 0 ends the loop through break, so the total is 5 + 7. Both statements sit at the top of the body, so a reader sees all the special cases first and the normal case last. This "guard clauses first" layout is a good default: the exceptions are dealt with and out of the way before the real work begins. (Real input needs more checks, for example for a word instead of a number; L07 shows one way.)

Backend Insight

Two real situations you will meet:

  • Searching. "Find the first order older than 30 days" ends at the first match, not after checking all million. Leaving early with break (or return, which you will learn with methods) saves work, and is the first step toward thinking about cost in BEG-039.
  • Skipping bad records. In a batch import, a row with a missing field is skipped with continue, logged, and the import carries on. One bad row should not stop a whole job. Be careful, though: silently skipping hides problems, so real code also records what it skipped.

Another point: a while (true) loop with a break is a loop whose end condition is hidden in the body. In team code, add a comment on the break that says what it means.

Common Mistakes

Mistake 1: Thinking break only leaves the current iteration

  • Incorrect: "break skips this lap." That is continue.
  • Correct: break ends the whole loop.

Mistake 2: continue in a while loop that skips the update

java
int i = 0;
while (i < 5) {
    if (i == 2) continue;   // i never changes again: infinite loop
    i++;
}

In a for, continue still runs the update. In a while, the update is in the body, so skipping the body can skip it too. Put the update before the continue, or use a for.

Mistake 3: Expecting break in a nested loop to leave both loops

It leaves only the innermost loop. The outer loop continues with its next iteration.

Mistake 4: Code after break in the same block

Statements after an unconditional break or continue can never run, and the compiler rejects them as unreachable.

Mistake 5: Using many exits

If you cannot explain in one sentence when the loop ends, there are too many breaks. Simplify the loop condition.

Exercises

Try each exercise yourself before opening the solutions.

Level A: Foundation

A1. What does this print?

java
for (int i = 1; i <= 5; i++) {
    if (i == 3) break;
    System.out.print(i + " ");
}
Show solution A1

A1. 1 2 then the loop ends at 3.

A2. What does it print if break is replaced by continue?

Show solution A2

A2. 1 2 4 5 : only 3 is skipped.

A3. Which statement ends the loop, and which skips only one iteration?

Show solution A3

A3. break ends the loop; continue skips one iteration.

Level B: Application

B1. Print the numbers 1 to 15 that are not multiples of 5, using continue.

Show solution B1

B1.

java
for (int i = 1; i <= 15; i++) {
    if (i % 5 == 0) continue;
    System.out.println(i);
}

B2. Starting at 1, print numbers until the square of the number exceeds 50, using while (true) and break. Print only numbers whose squares are 50 or less.

Show solution B2

B2.

java
int n = 1;
while (true) {
    if (n * n > 50) break;
    System.out.println(n);
    n++;
}

It prints 1 to 7 (7 squared is 49; 8 squared is 64).

B3. In the loop below, the programmer wants to skip 3 but the program hangs. Explain why and fix it.

java
int i = 1;
while (i <= 5) {
    if (i == 3) continue;
    System.out.println(i);
    i++;
}
Show solution B3

B3. When i is 3, continue jumps to the condition without running i++, so i stays 3 forever. Fix: increment before continue, or use a for loop:

java
for (int i = 1; i <= 5; i++) {
    if (i == 3) continue;
    System.out.println(i);
}

Level C: Challenge

C1. Write a loop that reads whole numbers until the user enters -1, ignores any number above 100, and prints the sum of the others and how many were counted.

Show solution C1

C1.

java
Scanner scanner = new Scanner(System.in);
int sum = 0, count = 0;
while (true) {
    int x = scanner.nextInt();
    if (x == -1) break;
    if (x > 100) continue;
    sum += x;
    count++;
}
System.out.println(sum + " from " + count + " numbers");

C2. A teammate's loop has break in an inner loop and expects the whole program section to stop. What do you tell them, and what simple change gives them what they want?

Show solution C2

C2. An unlabeled break leaves only the innermost loop, so the outer loop carries on. A simple fix without labels: set a boolean such as found = true before the break, and make the outer loop's condition (or its first line) check that flag. Another option, once you know methods, is to put the loops in a method and return.

Mini Challenge

Write a program that prints the numbers 1 to 30 as follows:

  1. Skip every number divisible by 4 using continue.
  2. Stop completely when the number is greater than 25 using break.
  3. After the loop print the last number printed. (Hint: keep it in a variable declared before the loop.)

Check your work: your output has 19 numbers, none divisible by 4, and the last number printed is 25.

Summary & Next Lesson

Key takeaways

  • break ends the innermost loop immediately; continue skips to the next iteration.
  • In a for, continue still runs the update; in a while, make sure the update is not skipped.
  • while (true) plus break fits loops that end in the middle of the body, such as sentinel input.
  • Do not change the loop variable inside the body; use break and continue instead.
  • Keep exits few and obvious.

Next lesson

The next lesson, "Nested loops", puts a loop inside a loop to handle rows and columns, and shows how to count how many times the body runs.

Self-check

  1. What does break do in a loop?
  2. What does continue do?
  3. In a for loop, what runs right after continue?
  4. In nested loops, which loop does an unlabeled break leave?
  5. What is a sentinel value?
Show answers
  1. It ends the loop immediately.
  2. It skips the rest of the current iteration and goes to the next one.
  3. The update (for example i++), followed by the condition check.
  4. Only the innermost loop.
  5. A special value, such as 0 or -1, that tells the loop to stop.

References

  • Oracle, Branching Statements (Java Tutorials). It supports that an unlabeled break ends the innermost switch, for, while, or do-while, and that continue skips the current iteration and moves to the loop's controlling expression.
  • Oracle, Java Language Specification, SE 21, Chapter 14. It supports that in a basic for, continue runs the update before the next condition check. Examples 1 and 2 were compiled and run with JDK 21; Example 3 was run with the piped input shown. The claim that the compiler rejects unreachable statements was confirmed by a compile in L06.

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.