Java Break and Continue

Java Break and Continue

The break and continue statements are used to control the flow of loops.


1. Java Break

The break statement is used to jump out of a loop or a switch statement.

When break is encountered inside a loop, the loop is immediately terminated, and the program control resumes at the next statement following the loop.

Break in a For Loop

public class Main {
  public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
      if (i == 4) {
        break; // Exit the loop when i is 4
      }
      System.out.println(i);
    }
    // The loop stops at 4, so it prints 0, 1, 2, 3
  }
}

2. Java Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

Continue in a For Loop

public class Main {
  public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
      if (i == 4) {
        continue; // Skip this iteration when i is 4
      }
      System.out.println(i);
    }
    // Prints 0, 1, 2, 3, 5, 6, 7, 8, 9
  }
}

Summary