Java Break & Continue
The break Statement
You’ve already seen the break statement when learning about the switch statement — it was used to jump out of the switch block. But guess what? You can also use break to jump out of a loop. When Java sees a break statement inside a loop, it immediately stops the loop — even if there are more iterations left.
Example: Stop the Loop When i Equals 4
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}0 1 2 3
The continue Statement
The continue statement skips one round of the loop when a condition is true — then moves on to the next iteration. It doesn’t stop the loop entirely — it just skips that one turn.
Example: Skip the Value 4
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}0 1 2 3 5 6 7 8 9
Good to Remember
Keyword | What it Does |
break | Stops the loop completely |
continue | Skips the current iteration, then continues the loop |
Combining break and continue
Skip 2 and Stop at 4
for (int i = 0; i < 6; i++) {
if (i == 2) {
continue; // skip this round
}
if (i == 4) {
break; // stop the loop completely
}
System.out.println(i);
}0 1 3
Using break and continue in while Loops
break in a While Loop
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
if (i == 4) {
break;
}
}0 1 2 3
continue in a While Loop
int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue; // skip number 4
}
System.out.println(i);
i++;
}0 1 2 3 5 6 7 8 9
Real-Life Example
Imagine you’re processing a list of numbers. You want to skip negative values, but stop completely if you find a zero.
int[] numbers = {3, -1, 7, 0, 9};
for (int n : numbers) {
if (n < 0) {
continue; // skip negative numbers
}
if (n == 0) {
break; // stop the loop when zero is found
}
System.out.println(n);
}3 7
Summary
Keyword | Meaning | Stops Loop | Skips Iteration | Used In |
break | End loop completely | Yes | No | for, while, do-while, switch |
continue | Skip current loop turn | No | Yes | for, while, do-while |