Programming and Java Fundamentals

Break, Continue, and Loop Control

ReadingPreview

You are viewing a free preview lesson.

Break and Continue

Lesson Overview

A loop normally continues until its condition becomes false.

However, sometimes we need to:

  • Stop a loop immediately when a target value is found
  • Skip an invalid value and move to the next iteration
  • Stop a menu when the user selects exit
  • Stop unnecessary work after a search result is found
  • Control execution inside nested loops

In Java, two main statements are used to change the normal flow of a loop:

  • break
  • continue

In this lesson, we will learn:

  • break
  • continue
  • Early loop termination
  • Search loops
  • Invalid value filtering
  • A common continue pitfall with while loops
  • Nested loop control
  • The basic concept of labeled break and continue

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.

Normal loop:

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

Output:

1
2
3
4
5

Using break, the loop can end early:

for (int number = 1; number <= 5; number++) {
    if (number == 3) {
        break;
    }

    System.out.println(number);
}

Output:

1
2

Using continue, only one iteration is skipped:

for (int number = 1; number <= 5; number++) {
    if (number == 3) {
        continue;
    }

    System.out.println(number);
}

Output:

1
2
4
5

break

break immediately terminates the nearest loop.

Syntax:

break;

Example:

for (int number = 1; number <= 10; number++) {
    if (number == 5) {
        break;
    }

    System.out.println(number);
}

Output:

1
2
3
4

When:

number == 5

becomes true, the loop stops.

break Ends Only the Loop

for (int number = 1; number <= 5; number++) {
    if (number == 3) {
        break;
    }

    System.out.println(number);
}

System.out.println("Loop finished");

Output:

1
2
Loop finished

break does not terminate the entire program.

It only terminates the current loop.

The Position of break Matters

break Before Printing

for (int number = 1; number <= 5; number++) {
    if (number == 3) {
        break;
    }

    System.out.println(number);
}

Output:

1
2

break After Printing

for (int number = 1; number <= 5; number++) {
    System.out.println(number);

    if (number == 3) {
        break;
    }
}

Output:

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.

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:

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

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:

Found: true

Using break in an Infinite Loop

Intentional infinite loop:

int number = 1;

while (true) {
    System.out.println(number);

    if (number == 5) {
        break;
    }

    number++;
}

Output:

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.

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;
}

Important:

if (number == -1) {
    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.

for (int number = 1; number <= 5; number++) {
    if (number == 3) {
        continue;
    }

    System.out.println(number);
}

Output:

1
2
4
5

The iteration for 3 is skipped.

How Does continue Work?

In a for loop:

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

for (int number = 1; number <= 10; number++) {
    if (number % 2 != 0) {
        continue;
    }

    System.out.println(number);
}

Output:

2
4
6
8
10

The odd numbers are skipped.

Skipping Invalid Values

int total = 0;

for (int number = -3; number <= 5; number++) {
    if (number < 0) {
        continue;
    }

    total += number;
}

System.out.println(total);

Processed values:

0
1
2
3
4
5

Output:

15

Using continue as a Guard

Suppose you want to process only even numbers.

Nested style:

for (int number = 1; number <= 10; number++) {
    if (number % 2 == 0) {
        int square =
                number * number;

        System.out.println(
                number + " -> " + square
        );
    }
}

Using continue:

for (int number = 1; number <= 10; number++) {
    if (number % 2 != 0) {
        continue;
    }

    int square =
            number * number;

    System.out.println(
            number + " -> " + square
    );
}

Output:

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:

int number = 0;

while (number < 5) {
    number++;

    if (number == 3) {
        continue;
    }

    System.out.println(number);
}

Output:

1
2
4
5

The counter is updated before continue.

Infinite Loop Caused by continue

Wrong:

int number = 1;

while (number <= 5) {
    if (number == 3) {
        continue;
    }

    System.out.println(number);

    number++;
}

When:

number = 3

then:

continue

executes.

Therefore:

number++;

is skipped.

number remains 3, and the loop continues indefinitely.

Safer while Structure

int number = 0;

while (number < 5) {
    number++;

    if (number == 3) {
        continue;
    }

    System.out.println(number);
}

Updating first avoids this particular problem.

break vs. continue

StatementEffect
breakTerminates the nearest loop
continueSkips only the current iteration

break

for (int number = 1; number <= 5; number++) {
    if (number == 3) {
        break;
    }

    System.out.println(number);
}

Output:

1
2

continue

for (int number = 1; number <= 5; number++) {
    if (number == 3) {
        continue;
    }

    System.out.println(number);
}

Output:

1
2
4
5

Nested Loops and break

A normal break terminates only the nearest loop.

for (int row = 1; row <= 3; row++) {
    for (int column = 1; column <= 3; column++) {
        if (column == 2) {
            break;
        }

        System.out.println(
                row + ", " + column
        );
    }
}

Output:

1, 1
2, 1
3, 1

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

The outer loop continues.

Nested Loops and continue

for (int row = 1; row <= 3; row++) {
    for (int column = 1; column <= 3; column++) {
        if (column == 2) {
            continue;
        }

        System.out.println(
                row + ", " + column
        );
    }
}

Output:

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

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

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.

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:

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

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:

Found at index: 11

Here:

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

Common Mistakes

Code After break

Wrong:

if (number == 3) {
    break;

    System.out.println("Stopped");
}

The statement after break cannot execute.

Correct:

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

    break;
}

Code After continue

Wrong:

if (number == 3) {
    continue;

    System.out.println("Skipped");
}

The statement after continue does not execute in the current iteration.

Expecting break to End Every Nested Loop

for (int row = 1; row <= 3; row++) {
    for (int column = 1; column <= 3; column++) {
        if (column == 2) {
            break;
        }
    }
}

Only the inner loop ends.

Checking the Sentinel After Processing It

Wrong:

total += number;

if (number == -1) {
    break;
}

This adds -1 to the total.

Correct:

if (number == -1) {
    break;
}

total += number;

Wrong continue Condition

Requirement:

Skip invalid marks.

Wrong:

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

This skips valid marks.

Correct:

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

Skipping the while Update

Wrong:

int number = 1;

while (number <= 5) {
    if (number == 3) {
        continue;
    }

    number++;
}

When number == 3, the counter no longer updates.

This can cause an infinite loop.

When Should You Use break?

break is useful when:

  • A search result has been found
  • An exit option is selected
  • A sentinel is received
  • Remaining iterations are unnecessary
  • The exit condition of an intentional infinite loop has been reached

When Should You Use continue?

continue is useful when:

  • An invalid value should be skipped
  • The current item should not be processed
  • Filtering is required
  • You want to write the main processing block without unnecessary nesting

Do Not Overuse Them

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

Hard to follow:

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

    if (...) {
        break;
    }

    if (...) {
        continue;
    }
}

Prefer:

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

Important Terms

Loop Control

Changing the normal execution flow of a loop.

break

Immediately terminates the nearest loop.

continue

Skips the remaining statements of the current iteration.

Early Termination

Ending a loop before its normal condition becomes false.

Filtering

Skipping values that should not be processed.

Labeled break

Exits up to a named outer loop.

Labeled continue

Starts the next iteration of a named outer loop.

Practice Exercise 1: Stop Before Five

Run a loop from 1 to 10.

Stop the loop when 5 is reached.

Expected:

1
2
3
4

Practice Exercise 2: Include Five

Stop the loop after printing 5.

Expected:

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

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

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:

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.

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

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

In this lesson, we learned:

  • break immediately terminates the nearest loop
  • continue skips the remaining code of the current iteration
  • break does not terminate the entire program
  • break is useful when a search result is found
  • A sentinel should be checked before it is processed
  • break can be used to exit an intentional infinite loop
  • continue is useful for skipping invalid or irrelevant values
  • continue can help keep the main loop logic flatter
  • In a for loop, continue moves execution to the update expression
  • In a while loop, skipping an update with continue can create an infinite loop
  • In nested loops, a normal break terminates only the nearest loop
  • Labeled break can exit an outer loop
  • Labeled continue can move to the next iteration of an outer loop
  • Labels are uncommon and should be used carefully
  • The position of break and continue changes program behavior
  • Excessive loop-control statements can make code harder to understand