The break Statement in Loops
You'll learn how to immediately exit a loop before it naturally completes, skipping all remaining iterations.
What is break?
The break statement is a control flow tool that lets you exit a loop instantly, no matter where you are in the loop's execution. When Java encounters break, it immediately jumps to the first line of code after the loop, ignoring any remaining iterations or code within the current loop body.
Think of it like an emergency exit door: instead of walking through the entire building (completing all iterations), you can leave immediately when you find what you're looking for or encounter a special condition.
How It Works
When break executes inside a loop (for, while, or do-while), the loop stops completely:
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop immediately when i equals 5
}
System.out.println(i);
}
System.out.println("Loop finished");
Output:
1
2
3
4
Loop finished
Notice that 5 never prints, and iterations 6 through 10 never happen. The loop terminates the moment break executes.
Common Use Cases
Use break when you're searching for something specific:
int target = 42;
boolean found = false;
for (int i = 0; i < 1000; i++) {
if (i == target) {
found = true;
break; // No need to check the remaining 957 numbers
}
}
Key Takeaway: The break statement immediately exits the innermost loop, skipping all remaining iterations and continuing execution right after the loop—perfect for early termination when a condition is met.