Java Break and Continue
Break and continue are statements that change how a loop runs. Break ends the loop at once, and continue skips the rest of the current pass.
Break stops the loop
The loop would print up to 9 without the break. The break fires when i reaches 3, before that value prints.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 3) {
break;
}
System.out.println(i);
}
}
}Continue skips one value
The continue fires when i is 3. That pass ends early, so 3 is missing from the printed sequence.
public class Main {
public static void main(String[] args) {
for (int i = 0; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
}
}
}Break inside a while loop
This while loop counts up from 1. The break fires when i reaches 4, before that value prints.
public class Main {
public static void main(String[] args) {
int i = 1;
while (i < 10) {
if (i == 4) {
break;
}
System.out.println(i);
i++;
}
}
}Example
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue;
}
if (i == 8) {
break;
}
System.out.println(i);
}
}
}Key points
- Break leaves the loop at once.
- Continue skips the rest of the current pass.
- After continue, the loop moves on to its next pass.
- Both statements often sit inside an if inside the loop.
- Break works in both for loops and while loops.
In this example, one loop uses both statements. The continue skips 5, so that value never prints. The break fires at 8 and ends the loop. The printed sequence stops at 7.
Note
Continue does not end the loop.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
What does continue do inside a loop?