Java - Break & Continue

In Java, break and continue are two control statements used in loops to alter the flow of control. They help in making the code more efficient and readable.

Break Statement

The break statement is used to break out of a loop prematurely. It is used inside a loop and when it is encountered, it immediately terminates the loop and transfers the control to the statement immediately following the loop.

Here is the basic syntax of break statement:

break;

Let's take an example to understand the usage of break statement. The following program prints the numbers from 1 to 10, but it terminates the loop when it reaches 5 using break statement.

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

Continue Statement

The continue statement is used to skip the current iteration of a loop and move to the next iteration. It is used inside a loop and when it is encountered, it skips the rest of the statements in the loop for the current iteration and starts the next iteration.

Here is the basic syntax of continue statement:

continue;

Let's take an example to understand the usage of continue statement. The following program prints the even numbers from 1 to 10, but it skips the odd numbers using continue statement.

public class ContinueExample {
  public static void main(String[] args) {
    for (int i = 1; i <= 10; i++) {
      if (i % 2 != 0) {
        continue;
      }
      System.out.print(i + " ");
    }
  }
}

In this example, the if statement checks if the number is odd. If it is odd, the continue statement skips the rest of the statements in the loop for that iteration and starts the next iteration.

That's it! This is a basic tutorial on the break and continue statements in Java. These statements are widely used in loops and can help in making your code more efficient and readable.