break vs continue: When to Use Each
What You'll Learn
You'll discover the key differences between break and continue, and learn when each statement is the right tool for controlling loop flow.
The Core Difference
Think of a loop as walking through a hallway of doors. break means "exit the hallway entirely" — you stop the loop and move on to whatever code comes after it. continue means "skip this door and move to the next one" — you skip the rest of the current iteration but keep looping.
Using break: Early Exit
Use break when you've found what you're looking for or hit a condition that makes continuing the loop pointless:
// Find the first negative number
for (int i = 0; i < 100; i++) {
if (numbers[i] < 0) {
System.out.println("Found negative at index " + i);
break; // Stop searching entirely
}
}
Using continue: Skip and Keep Going
Use continue when you want to skip certain iterations but process the rest:
// Print only positive numbers
for (int i = 0; i < 10; i++) {
if (numbers[i] <= 0) {
continue; // Skip this iteration, move to next i
}
System.out.println(numbers[i]); // Only reached for positive
}
When to Choose Which
- Choose
breakwhen: You need to stop the entire loop early (found a match, hit an error condition, reached a limit) - Choose
continuewhen: You want to skip processing for specific cases but keep checking remaining items (filtering, validation)
Real-World Analogy
Imagine checking emails: break is like finding an urgent message and stopping your review to handle it immediately. continue is like skipping spam messages but continuing to review your inbox.
Key Takeaway: Use break to exit a loop completely when you're done; use continue to skip the current iteration's remaining code while staying in the loop.