Skip to content

3.4 Break and Continue

In Java, break and continue are control flow statements that allow you to alter the normal flow of loops. They are particularly useful for managing iterations in for, while, and do-while loops.

The break Statement

The break statement is used to exit a loop prematurely. When encountered, it immediately terminates the loop and transfers control to the statement following the loop.

Syntax

java
break;

Example

java
for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        break; // Exit the loop when i equals 5
    }
    System.out.println(i);
}

Output:

1
2
3
4

In this example, the loop stops when i equals 5, and the numbers 1 through 4 are printed.

The continue Statement

The continue statement skips the current iteration of the loop and moves to the next iteration. It does not terminate the loop but allows you to skip specific cases.

Syntax:

java
continue;

Example:

java
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue; // Skip even numbers
    }
    System.out.println(i);
}

Output:

1
3
5
7
9

In this example, the loop skips even numbers and prints only odd numbers.

Using break and continue in while Loops

Example with break

java
int i = 1;
while (i <= 10) {
    if (i == 5) {
        break; // Exit the loop when i equals 5
    }
    System.out.println(i);
    i++;
}

Output:

1
2
3
4

Example with continue

java
int i = 0;
while (i < 10) {
    i++;
    if (i % 2 == 0) {
        continue; // Skip even numbers
    }
    System.out.println(i);
}

Output:

1
3
5
7
9

Key Points

  1. break: Use to exit a loop entirely.
  2. continue: Use to skip the current iteration and proceed to the next.
  3. Readability: Use these statements sparingly to maintain code clarity.
  4. Nested Loops: In nested loops, break and continue affect only the innermost loop.

Common Pitfalls

  1. Infinite Loops: Ensure break or continue does not cause unintended infinite loops.
  2. Logic Errors: Misusing break or continue can lead to unexpected behavior. Test thoroughly.

break and continue are powerful tools for controlling loop execution. Use them wisely to write efficient and readable code.