Understanding Java Break and Continue Statements
In Java, the break and continue statements are used to control the flow of loops.
break Statement:
The break statement is used to terminate the execution of a loop prematurely. When encountered, it
immediately exits the loop, and the program continues with the next statement after the loop.
for (int i = 1; i <= 10; i++) {
if (i == 5) {
System.out.println("Breaking the loop at i = " + i);
break;
}
System.out.println("Iteration " + i);
}
continue Statement:
The continue statement is used to skip the rest of the code inside a loop for the current iteration
and move to the next iteration.
for (int j = 1; j <= 5; j++) {
if (j == 3) {
System.out.println("Skipping iteration at j = " + j);
continue;
}
System.out.println("Iteration " + j);
}
Example:
Here's an example demonstrating the use of break and continue statements in Java:
// Use of break statement
for (int x = 1; x <= 10; x++) {
if (x == 7) {
System.out.println("Breaking the loop at x = " + x);
break;
}
System.out.println("Iteration " + x);
}
// Use of continue statement
System.out.println("\nUsing continue statement:");
for (int y = 1; y <= 5; y++) {
if (y == 3) {
System.out.println("Skipping iteration at y = " + y);
continue;
}
System.out.println("Iteration " + y);
}
Note:
The break and continue statements provide additional control within loops. While
break terminates the entire loop, continue skips the rest of the code in the current
iteration and moves to the next one.