Java for Beginners, Lesson 20: break, continue and Labelled Loops in Java

Java for Beginners · Module 4: Control Flow


🎯 Changing the Flow Inside a Loop

Normally a loop runs until its condition fails. But sometimes you want to stop early (you found what you needed) or skip one pass (that value should be ignored). Java gives you two jump statements for this: break and continue.

📌 break leaves the loop completely. continue skips the rest of the current pass and goes straight to the next one.
StatementWhat it doesTypical use
breakleaves the loop (or switch) right nowstop when the answer is found
continueskips the rest of this pass and starts the nextignore unwanted values
break labelleaves the loop that carries the labelexit nested loops at once
continue labeljumps to the next pass of the labelled loopskip a whole row

Figure 1: Jump statements inside loops.

1️⃣ break

ii == 5 ?ActionPrinted so far
1noprint1
2noprint1 2
3noprint1 2 3
4noprint1 2 3 4
5yesbreak: loop ends1 2 3 4

Figure 2: Tracing break: the loop ends when i reaches 5.

Program 1: Stopping early

public class BreakDemo {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                break;
            }
            System.out.print(i + " ");
        }
        System.out.println();
        System.out.println("Loop stopped early");

        int[] marks = {72, 55, 0, 81};
        int found = -1;
        for (int i = 0; i < marks.length; i++) {
            if (marks[i] == 0) {
                found = i;
                break;
            }
        }
        System.out.println("First zero at index " + found);
    }
}
🖥️ Output:
1 2 3 4
Loop stopped early
First zero at index 2
  • When i reaches 5, break ends the loop immediately. The numbers 5 to 10 are never printed.
  • The second loop is a search: as soon as the zero is found, there is no reason to check the rest. break saves the work.
  • Starting found at -1 is a common way to say “not found yet”. Arrays and marks.length are explained in Lesson 21.
  • break also ends a switch case (Lesson 17).

2️⃣ continue

ii % 2 == 0 ?Action
1noprint 1
2yescontinue: skip print
3noprint 3
4yescontinue: skip print
5noprint 5

Figure 3: Tracing continue: even numbers are skipped, the loop goes on.

Program 2: Skipping some passes

public class ContinueDemo {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i % 2 == 0) {
                continue;
            }
            System.out.print(i + " ");
        }
        System.out.println();

        int sum = 0;
        int[] data = {5, -3, 8, -1, 4};
        for (int d : data) {
            if (d < 0) {
                continue;
            }
            sum += d;
        }
        System.out.println("Sum of positives = " + sum);
    }
}
🖥️ Output:
1 3 5 7 9
Sum of positives = 17
  • For even numbers, continue skips the print and jumps to the next i. The loop itself does not end.
  • In a for loop, continue still runs the update (i++). In a while loop you must make sure the update is done before the continue, or the loop may never end.
  • The second loop adds only the positive numbers: 5 + 8 + 4 = 17.

3️⃣ Labelled break and continue

A plain break or continue affects only the innermost loop. To reach an outer loop, give it a label, which is a name followed by a colon, and use that name after break or continue.

outer loop
label: outer
inner loop
plain break leaves only this loop
break outer; jumps out of both loops. continue outer; jumps to the next pass of the outer loop.

Figure 4: A label lets break and continue reach an outer loop.

public class LabelDemo {
    public static void main(String[] args) {
        System.out.println("Plain break (inner only):");
        for (int r = 1; r <= 3; r++) {
            for (int c = 1; c <= 3; c++) {
                if (c == 2) break;
                System.out.println("r=" + r + " c=" + c);
            }
        }

        System.out.println("Labelled break (leaves both loops):");
        outer:
        for (int r = 1; r <= 3; r++) {
            for (int c = 1; c <= 3; c++) {
                if (r == 2 && c == 2) break outer;
                System.out.println("r=" + r + " c=" + c);
            }
        }

        System.out.println("Labelled continue:");
        rows:
        for (int r = 1; r <= 3; r++) {
            for (int c = 1; c <= 3; c++) {
                if (c == 2) continue rows;
                System.out.println("r=" + r + " c=" + c);
            }
        }
    }
}
🖥️ Output:
Plain break (inner only):
r=1 c=1
r=2 c=1
r=3 c=1
Labelled break (leaves both loops):
r=1 c=1
r=1 c=2
r=1 c=3
r=2 c=1
Labelled continue:
r=1 c=1
r=2 c=1
r=3 c=1
  • Plain break: each time c reaches 2, only the inner loop ends. The outer loop carries on to the next r.
  • break outer: when r = 2 and c = 2, both loops end at once. Row 3 is never visited.
  • continue rows: when c = 2, the program jumps to the next r, skipping the rest of the inner loop.
  • Labels are rare in everyday code. Use them only when exiting nested loops is truly needed.

4️⃣ Useful Patterns

Program 4: Prime test with break

public class Prime {
    public static void main(String[] args) {
        int[] tests = {17, 20, 29, 1};
        for (int n : tests) {
            boolean prime = n > 1;
            for (int d = 2; d * d <= n; d++) {
                if (n % d == 0) {
                    prime = false;
                    break;
                }
            }
            System.out.println(n + (prime ? " is prime" : " is not prime"));
        }
    }
}
🖥️ Output:
17 is prime
20 is not prime
29 is prime
1 is not prime
  • A number is not prime as soon as one divisor is found, so the inner loop can break at once.
  • Checking only up to the square root (d * d <= n) is enough, since any larger divisor would pair with a smaller one.

Program 5: An intentional infinite loop that ends with break

import java.util.Scanner;

public class Guess {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int secret = 7;
        while (true) {
            System.out.print("Guess: ");
            int g = sc.nextInt();
            if (g == secret) {
                System.out.println("Correct!");
                break;
            }
            System.out.println(g < secret ? "Too low" : "Too high");
        }
    }
}
🖥️ Output (bold = what the user types):
Guess: 3
Too low
Guess: 9
Too high
Guess: 7
Correct!
  • while (true) never ends by itself. The only exit is the break when the guess is right.
  • This is a common way to write “repeat until the user succeeds”.

5️⃣ Errors Beginners Meet

break outside a loop or switch

public class Bad1 {
    public static void main(String[] args) {
        int x = 5;
        if (x > 3) {
            break;
        }
    }
}
🖥️ Compiler message:
Bad1.java:5: error: break outside switch or loop
break;
^
1 error
  • break needs a loop or switch around it. An if alone is not enough.

A label that does not exist

public class Bad2 {
    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            System.out.println(i);
            continue outer;
        }
    }
}
🖥️ Compiler message:
Bad2.java:5: error: undefined label: outer
continue outer;
^
1 error
  • The label must be written just before the loop it names, as in outer: for (...).

⚠️ Common Mistakes

MistakeProblemFix
Expecting break to leave both nested loopsOnly the inner loop endsUse a label, or a flag
continue in a while loop before the updateInfinite loopUpdate the counter first
Code after break in the same blockUnreachable: compile errorRemove it
Using break to avoid thinking about the conditionConfusing loopsPrefer a clear condition when possible
Confusing break and continueWhole loop ends versus one pass skippedTrace one example by hand

❓ Frequently Asked Questions

Q1. Is there a goto in Java?
goto is a reserved word but it is not used. Labelled break and continue cover the legitimate cases.

Q2. What is the difference between break and return?
break leaves only the loop. return leaves the whole method (Lesson 25).

Q3. Can I use continue inside a switch?
Yes, if the switch is inside a loop. It moves to the next pass of that loop.

Q4. Do labels have to be in capitals?
No. It is only a convention to make them stand out.

✅ Key Takeaways

  • break ends the loop (or switch) immediately.
  • continue skips to the next pass of the loop.
  • Both affect only the innermost loop, unless you add a label.
  • while (true) with a break is a valid “repeat until” pattern.
  • Use break for searches and early exits, and continue to skip unwanted values.

🔁 Module 4 Recap

Lessons 16 to 20 gave you every control-flow tool: if, switch, while, do-while, for, break and continue. In Module 5 you will start storing collections of data with arrays and strings.

🎓 Practice questions: (1) Read numbers until the user enters 0, then print their sum. (2) Print the numbers 1 to 20 but skip multiples of 3. (3) Search an array for a value and print its index, or “not found”. (4) What is the output of a nested loop where the inner loop contains break at c == 2? (5) Rewrite the guessing game so it stops after 3 wrong guesses.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision