Break and Continue Statements in Java

In Java, the break and continue statements are used to control the flow of a loop. These statements allow you to alter the normal execution of loops, giving you more flexibility and control.

The Break Statement

The break statement is used to exit a loop prematurely. When the break statement is encountered within a loop, the loop is immediately terminated, and the program execution continues with the next statement after the loop.

Here is the syntax of the break statement:

break;

Example:

for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        break;
    }
    System.out.println(i);
}

In the above example, the loop will iterate from 1 to 5. However, when i becomes 3, the break statement is encountered, and the loop is terminated. Thus, the output will be:

1
2

The Continue Statement

Unlike the break statement, the continue statement does not terminate the loop. Instead, it skips the remaining statements within the loop for the current iteration and moves to the next iteration.

Here is the syntax of the continue statement:

continue;

Example:

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

In the above example, when i becomes 3, the continue statement is encountered. As a result, the remaining statements within the loop for that iteration are skipped, and the loop proceeds with the next iteration. Thus, the output will be:

1
2
4
5

Usage Scenarios

The break and continue statements can be used in various scenarios where you need to control the flow of loops based on certain conditions. Here are a few common use cases:

  • Breaking out of a loop early: You can use the break statement to terminate a loop if a specific condition is met, allowing you to exit the loop prematurely.
  • Skipping unwanted iterations: The continue statement is useful when you want to skip over certain iterations of a loop based on specific conditions. It allows you to bypass the execution of remaining statements within the loop for the current iteration and proceed to the next iteration.

Conclusion

The break and continue statements are powerful tools in Java that give you control over the execution of loops. Whether you need to exit a loop prematurely or skip unwanted iterations, these statements can help you achieve the desired flow control. Use them wisely to make your loops more efficient and flexible.


noob to master © copyleft