In Java, the "break" and "continue" statements provide control flow mechanisms that allow you to modify the behavior of loops. These statements help in enhancing the flexibility and efficiency of your code. In this blog post, we will explore the syntax and usage of the "break" and "continue" statements, along with relevant examples.
The "break" statement is used to exit a loop prematurely. When encountered, the "break" statement terminates the loop's execution and transfers control to the next statement after the loop. It is often used when a specific condition is met, and there is no need to continue iterating. Here's the syntax of the "break" statement.
break;
public class BreakExample { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { if (i == 3) { break; } System.out.println("Iteration: " + i); } } }
In the above example, the "break" statement is used inside a "for" loop. When the loop reaches the iteration where "i" is equal to 3, the "break" statement is executed, and the loop is terminated. As a result, only two iterations are printed: "Iteration: 1" and "Iteration: 2".
The "continue" statement is used to skip the rest of the loop's current iteration and move to the next iteration. When encountered, the "continue" statement jumps to the next iteration without executing the remaining code within the loop for that particular iteration. Here's the syntax of the "continue" statement:
continue;
public class ContinueExample { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { if (i == 3) { continue; } System.out.println("Iteration: " + i); } } }
In the above example, the "continue" statement is used inside a "for" loop. When the loop reaches the iteration where "i" is equal to 3, the "continue" statement is executed, and the remaining code within the loop for that iteration is skipped. As a result, "Iteration: 3" is not printed, and the loop continues with the next iteration, printing "Iteration: 4" and "Iteration: 5".