Õppetund 19/140
Kirjalik õppetund · 14 min

Break, Continue, and Loop Control

Control loops with `break` and `continue` to stop a search early, skip invalid values and leave a controlled infinite loop.

Eelvaade

Vaatad tasuta eelvaate õppetundi.

Lesson Overview

A loop normally continues until its condition becomes false. Sometimes that is too rigid: a search should stop as soon as the target is found, an invalid value should be skipped without stopping everything, and a menu loop should end the moment the user chooses Exit.

In Java, two statements change the normal flow of a loop: break and continue. Used well, they make loops shorter and clearer; used carelessly, they create infinite loops and control flow that is hard to follow. This lesson covers both sides.

Learning Objectives

After completing this lesson, you will be able to:

  • Terminate a loop early using break
  • Skip the current iteration using continue
  • Stop a search loop when a result is found
  • Skip invalid values
  • Exit a controlled infinite loop
  • Understand how break and continue behave in nested loops
  • Identify common loop-control mistakes

What Is Loop Control?

A loop-control statement changes the normal execution flow of a loop. A normal for loop from 1 to 5 prints all five numbers. Using break, the loop can end early:

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

Output:

text
1
2

Using continue, only one iteration is skipped:

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

Output:

text
1
2
4
5

break

break; immediately terminates the nearest loop. It does not terminate the entire program: execution continues with the first statement after the loop:

java
for (int number = 1; number <= 5; number++) {
    if (number == 3) {
        break;
    }
    System.out.println(number);
}
System.out.println("Loop finished");

Output:

text
1
2
Loop finished

The Position of break Matters

In the examples so far, break comes before printing, so 3 is never printed. With break after printing:

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

Output:

text
1
2
3

Statement order changes the result.

break in a Search Loop

Suppose we need to find the index of the first 'F' character in a String:

java
String text = "Java Foundation";
char target = 'F';
int foundIndex = -1;
for (int index = 0; index < text.length(); index++) {
    if (text.charAt(index) == target) {
        foundIndex = index;
        break;
    }
}
System.out.println("Found index: " + foundIndex);

Output:

text
Found index: 5

Once the target is found, there is no need to check the remaining characters. Therefore, break is very useful in search loops.

Checking Whether a Target Was Found

java
String text = "Learn Java";
char target = 'J';
boolean found = false;
for (int index = 0; index < text.length(); index++) {
    if (text.charAt(index) == target) {
        found = true;
        break;
    }
}
System.out.println("Found: " + found);

Output:

text
Found: true

Using break in an Infinite Loop

Here is an intentional infinite loop:

java
int number = 1;
while (true) {
    System.out.println(number);
    if (number == 5) {
        break;
    }
    number++;
}

Output:

text
1
2
3
4
5

while (true) does not terminate on its own. Here, break acts as the exit condition.

Sentinel and break

Suppose -1 is the signal to end an input sequence:

java
int total = 0;
while (true) {
    System.out.print("Enter a number or -1 to stop: ");
    int number = Integer.parseInt(scanner.nextLine().strip());
    if (number == -1) {
        break;
    }
    total += number;
}

The if (number == -1) check with its break appears before processing. Therefore, the sentinel is not added to the total.

continue

continue does not terminate the entire loop. It skips the remaining statements in the current iteration and moves to the next iteration, as the second example in What Is Loop Control? showed: the iteration for 3 is skipped, and the loop goes on with 4 and 5.

How Does continue Work?

In a for loop:

java
for (initialization; condition; update) {
    if (skipCondition) {
        continue;
    }
    // Remaining statements
}

When continue executes:

  1. The remaining body of the current iteration is skipped
  2. The update expression executes
  3. The condition is checked again
  4. The next iteration begins

Even Numbers with continue

java
for (int number = 1; number <= 10; number++) {
    if (number % 2 != 0) {
        continue;
    }
    System.out.println(number);
}

Output:

text
2
4
6
8
10

The odd numbers are skipped.

Skipping Invalid Values

java
int total = 0;
for (int number = -3; number <= 5; number++) {
    if (number < 0) {
        continue;
    }
    total += number;
}
System.out.println(total);

Processed values:

text
0
1
2
3
4
5

Output:

text
15

Using continue as a Guard

Suppose you want to process only even numbers. Nested style:

java
for (int number = 1; number <= 10; number++) {
    if (number % 2 == 0) {
        int square = number * number;
        System.out.println(number + " -> " + square);
    }
}

Using continue:

java
for (int number = 1; number <= 10; number++) {
    if (number % 2 != 0) {
        continue;
    }
    int square = number * number;
    System.out.println(number + " -> " + square);
}

Output:

text
2 -> 4
4 -> 16
6 -> 36
8 -> 64
10 -> 100

Skipping invalid or irrelevant cases early can often make the main logic flatter and easier to read.

continue in a while Loop

When using continue in a while loop, the counter update must be handled carefully. Correct:

java
int number = 0;
while (number < 5) {
    number++;
    if (number == 3) {
        continue;
    }
    System.out.println(number);
}

Output:

text
1
2
4
5

The counter is updated before continue.

Infinite Loop Caused by continue

Wrong:

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

When number is 3, continue executes, so number++; is skipped. number remains 3, and the loop continues indefinitely.

Safer while Structure

The correct example above updates number at the start of the body, before continue can run. Updating first avoids this particular problem.

break vs. continue

StatementEffect
breakTerminates the nearest loop
continueSkips only the current iteration

The examples in "What Is Loop Control?" show both side by side: with break the output is 1 2, and with continue it is 1 2 4 5.

Nested Loops

Nested Loops and break

A normal break terminates only the nearest loop:

java
for (int row = 1; row <= 3; row++) {
    for (int column = 1; column <= 3; column++) {
        if (column == 2) {
            break;
        }
        System.out.println(row + ", " + column);
    }
}

Output:

text
1, 1
2, 1
3, 1

The inner loop ends at column == 2 for each row. The outer loop continues.

Nested Loops and continue

java
for (int row = 1; row <= 3; row++) {
    for (int column = 1; column <= 3; column++) {
        if (column == 2) {
            continue;
        }
        System.out.println(row + ", " + column);
    }
}

Output:

text
1, 1
1, 3
2, 1
2, 3
3, 1
3, 3

Only the column == 2 iteration of the inner loop is skipped.

Labeled break and continue

Labeled break

Java supports labels when you need to exit an outer loop from inside a nested loop:

java
search:
for (int row = 1; row <= 3; row++) {
    for (int column = 1; column <= 3; column++) {
        if (row == 2 && column == 3) {
            break search;
        }
        System.out.println(row + ", " + column);
    }
}

break search; terminates the labeled outer loop. As a beginner, you only need to recognize the concept. Using labels more than necessary can make control flow difficult to follow.

Labeled continue

Java also supports labeled continue to move to the next iteration of an outer loop:

java
outer:
for (int row = 1; row <= 3; row++) {
    for (int column = 1; column <= 3; column++) {
        if (column == 2) {
            continue outer;
        }
        System.out.println(row + ", " + column);
    }
}

Output:

text
1, 1
2, 1
3, 1

When column 2 is reached, the remaining work for the current row is skipped and the next row begins. Labeled control flow is uncommon. If the problem can be solved using simpler loop logic, prefer that approach.

Complete Example: Search First Match

java
public class Main {

    public static void main(String[] args) {
        String text = "Production Java";
        char target = 'J';
        int foundIndex = -1;

        for (int index = 0; index < text.length(); index++) {
            if (text.charAt(index) != target) {
                continue;
            }
            foundIndex = index;
            break;
        }

        if (foundIndex >= 0) {
            System.out.println("Found at index: " + foundIndex);
        } else {
            System.out.println("Character not found");
        }
    }
}

Output:

text
Found at index: 11

Here:

  • Non-matching character → continue
  • Match found → store the index
  • Remaining search is unnecessary → break

When Should You Use break and continue?

Use break when the remaining iterations are unnecessary: a search result has been found, the user selected Exit, a sentinel arrived, or an intentional while (true) loop has reached its exit condition. Use continue to skip an item that should not be processed (filtering invalid values) and keep the main processing block free of extra nesting.

Do Not Overuse Them

A loop containing many break and continue statements can become difficult to follow. Hard to follow:

java
for (...) {
    if (...) {
        continue;
    }
    if (...) {
        break;
    }
    if (...) {
        continue;
    }
}

Prefer:

  • Clear conditions
  • Meaningful boolean variables
  • Small loop bodies
  • Simple control flow

Predict the Result

Question 1

java
for (int number = 1; number <= 10; number++) {
    if (number % 3 == 0) {
        continue;
    }
    if (number > 7) {
        break;
    }
    System.out.print(number + " ");
}

What does this print?

Answer

1 2 4 5 7 . continue skips 3 and 6. At 8 the condition number > 7 is true, so break ends the loop before 9 and 10 are reached.

Question 2

java
for (int row = 1; row <= 3; row++) {
    for (int column = 1; column <= 3; column++) {
        if (column == 2) {
            break;
        }
        System.out.println(row + "," + column);
    }
}

What does this print?

Answer

text
1,1
2,1
3,1

break exits only the innermost loop. The outer loop continues with the next row.

Question 3

java
for (int number = 1; number <= 3; number++) {
    switch (number) {
        case 2:
            System.out.println("Two");
            break;
        default:
            System.out.println(number);
    }
}

What does this print?

Answer

text
1
Two
3

Inside a traditional switch, break leaves the switch, not the loop, so the loop still reaches 3.

Question 4

java
for (int number = 1; number <= 5; number++) {
    if (number == 3) {
        break;
        System.out.println("Found 3");
    }
}

Will it compile?

Answer

No: unreachable statement. Nothing after break in the same block can ever run, and Java reports that as an error.

Common Mistakes

Code After break or continue

Wrong:

java
if (number == 3) {
    break;
    System.out.println("Stopped");
}

The statement after break can never execute, so this code does not compile. javac reports error: unreachable statement. The same happens with a statement after continue. Put the statement before break:

java
if (number == 3) {
    System.out.println("Stopped");
    break;
}

Checking the Sentinel After Processing It

Wrong:

java
total += number;
if (number == -1) {
    break;
}

This adds -1 to the total. Correct:

java
if (number == -1) {
    break;
}
total += number;

Wrong continue Condition

Requirement:

Skip invalid marks.

Wrong:

java
if (mark >= 0 && mark <= 100) {
    continue;
}

This skips valid marks. Correct:

java
if (mark < 0 || mark > 100) {
    continue;
}

Practice Exercise 1: Stop Before Five

Solutions: lesson 1.25.

Run a loop from 1 to 10. Stop the loop when 5 is reached. Expected:

text
1
2
3
4

Practice Exercise 2: Include Five

Stop the loop after printing 5. Expected:

text
1
2
3
4
5

Practice Exercise 3: Skip Five

Print from 1 to 10, but do not print 5.

Practice Exercise 4: Even Numbers

Use continue to skip odd numbers from 1 to 20 and print only even numbers.

Practice Exercise 5: Character Search

java
String text = "Java Foundation";

Find the index of the first 'a' character and stop the loop as soon as a match is found.

Practice Exercise 6: Sentinel Total

The user enters numbers. When -1 is entered, stop the loop. Do not add the sentinel to the total.

Practice Exercise 7: Fix the Infinite Loop

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

Explain the problem and fix it.

Practice Exercise 8: Nested break

Create a 3 × 3 nested loop. For each row, stop the inner loop when column 2 is reached. Expected:

text
1, 1
2, 1
3, 1

Practice Exercise 9: Labeled break

Inside a nested loop, exit both loops when the coordinate 2, 3 is found.

Practice Exercise 10: Filtering

Iterate through the numbers from 1 to 20. Skip numbers that are not divisible by 3, and print only the divisible numbers.

Knowledge Check

Question 1

What does break do?

Question 2

What does continue do?

Question 3

Does break terminate the entire program?

Question 4

Does continue terminate the entire loop?

Question 5

Why is break useful in a search loop?

Question 6

What executes after continue in a for loop?

Question 7

Why can continue cause an infinite loop in a while loop?

Question 8

Which loop does a normal break terminate in a nested loop?

Question 9

What does labeled break do?

Question 10

What does labeled continue do?

Question 11

When should a sentinel be checked?

Question 12

Which statement is useful for filtering invalid values?

Question 13

What is the main difference between break and continue?

Question 14

What problem can occur if break or continue is overused?

Knowledge Check Answers

Answer 1

It immediately terminates the nearest loop.

Answer 2

It skips the remaining statements of the current iteration and moves to the next iteration.

Answer 3

No. It terminates only the nearest loop.

Answer 4

No.

Answer 5

Once the target is found, unnecessary remaining iterations can be stopped.

Answer 6

The for loop's update expression executes, then the condition is checked again.

Answer 7

If the counter update appears after continue, that update can be skipped, causing the condition variable to remain stuck at the same value.

Answer 8

The nearest or innermost loop.

Answer 9

It can terminate execution up to a named outer loop.

Answer 10

It can start the next iteration of a named outer loop.

Answer 11

Before processing the sentinel as normal data.

Answer 12

java
continue;

Answer 13

break terminates the loop, while continue skips only the current iteration.

Answer 14

Control flow can become harder to read, debug, and maintain.

Lesson Summary

  • break immediately terminates the nearest loop; the program continues after the loop.
  • continue skips the rest of the current iteration; in a for loop, the update runs next and the condition is checked again.
  • break is useful in search loops, for sentinels, and as the exit of an intentional while (true) loop.
  • continue is useful for skipping invalid values and keeping the main logic flat.
  • In a while loop, update the counter before continue, or the update can be skipped and the loop never ends.
  • In nested loops, a normal break or continue affects only the innermost loop. Labeled break and continue target an outer loop, but use them sparingly.
  • Check a sentinel before processing it, and avoid filling one loop with many break and continue statements.

Mõtle enne

Tulekul

Kontrollküsimused, mille puhul valid vastuse enne, kui õppetund selle näitab.