Java Break and Continue Statements

The break and continue statements in Java are used to alter the flow of loops. The break statement terminates the loop entirely, while the continue statement skips the current iteration and proceeds to the next one.

Key Topics

1. Break Statement

The break statement exits the loop immediately when encountered.

for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        break;
    }
    System.out.println(i);
}
// Output: 1 2 3 4

2. Continue Statement

The continue statement skips the current iteration and continues with the next one.

for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        continue;
    }
    System.out.println(i);
}
// Output: 1 2 4 5

3. Examples

3.1 Using Break in a Loop

public class BreakExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 7) {
                break;
            }
            System.out.println(i);
        }
    }
}

3.2 Using Continue in a Loop

public class ContinueExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 2 || i == 4) {
                continue;
            }
            System.out.println(i);
        }
    }
}

4. Labeled Break and Continue

Labels can be used with break and continue to control outer loops in nested loops.

outerLoop:
for (int i = 1; i <= 5; i++) {
    for (int j = 1; j <= 5; j++) {
        if (i * j > 6) {
            break outerLoop;
        }
        System.out.println(i + " * " + j + " = " + (i * j));
    }
}

Key Takeaways

  • break exits the loop immediately.
  • continue skips the current iteration and continues with the next.
  • Use labels with break and continue to control nested loops.
  • These statements should be used judiciously to maintain code readability.