The break and continue statements are used to control the flow of loops.
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.
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
}
}
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:
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
}
}
break to exit a loop entirely.continue to skip the current iteration and move to the next one.