Difference between break and continue statement
In Java, the break
and continue
statements are used to control the flow of a loop.
The break
statement is used to exit a loop early. When a break
statement is encountered inside a loop, the loop is immediately terminated, and the program continues with the next statement after the loop.
For example:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
In this example, the break
statement is encountered when i
is 5, so the loop is terminated, and the program continues with the next statement after the loop. The output of this program is:
0 1 2 3 4
The continue
statement is used to skip the rest of the current iteration of a loop, and continue with the next iteration. When a continue
statement is encountered inside a loop, the program skips the rest of the current iteration and continues with the next iteration.
For example:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
In this example, the continue
statement is encountered when i
is an even number, so the rest of the current iteration is skipped, and the program continues with the next iteration. The output of this program is:
1 3 5 7 9
I hope this helps! Let me know if you have any questions.