Java Break and Continue
Sometimes you need finer control over a loop than just its condition. The break statement lets you jump out of a loop early, and the continue statement lets you skip the rest of the current pass and move on to the next one. Together they give you precise control over how a loop flows.
Stopping early with break
When Java reaches a break statement, it immediately leaves the loop, ignoring any remaining passes. This is handy when you have found what you were looking for and there is no reason to keep going.
Break out of a loop
for (int i = 1; i <= 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
// Output:
// 1
// 2
// 3The loop was set up to count to 10, but as soon as i reached 4 the break statement ended it. Nothing after 3 was printed because the loop stopped entirely.
Skipping a pass with continue
The continue statement does not end the loop. Instead it skips the rest of the code in the current pass and jumps straight to the next one. Here we print only the odd numbers by skipping the even ones.
Skip even numbers with continue
for (int i = 1; i <= 6; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
// Output:
// 1
// 3
// 5Break and continue at a glance
- break exits the entire loop right away.
- continue skips only the current pass and continues looping.
- Both work in while, do/while, and for loops.
- In nested loops, they affect only the innermost loop that contains them.
Searching a list, then stopping
String[] names = {"Ana", "Ben", "Cara", "Dev"};
String target = "Cara";
for (int i = 0; i < names.length; i++) {
if (names[i].equals(target)) {
System.out.println("Found at position " + i);
break;
}
}
// Output: Found at position 2Exercise: Java Break and Continue
What does the break statement do when executed inside a loop?