Break and Continue in Java
Introduction
In Java, loops (like for, while, and do-while) are designed to run until their condition evaluates to false. However, there are scenarios where you need to alter this normal execution flow based on specific conditions. Java provides two keywords for this: break and continue.
1. The break Statement
The break statement is used to instantly terminate the loop it is inside. Once a break is executed, the program control jumps to the very next statement immediately following the loop.
- Common Use Case: Exiting a loop early once a target value is found (like in a linear search) to save processing time.
Example: Basic Break
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
System.out.println("Breaking at 5!");
break; // Loop terminates here
}
System.out.println(i);
}
System.out.println("Loop finished.");
// Output: 1, 2, 3, 4, Breaking at 5!, Loop finished.
}
}
2. The continue Statement
Unlike break, the continue statement does NOT terminate the loop. Instead, it skips the current iteration and instantly jumps to the next iteration (evaluating the loop condition or increment step).
- Common Use Case: Filtering out specific values (like skipping even numbers) without stopping the entire process.
Example: Basic Continue
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skips printing 3
}
System.out.println(i);
}
// Output: 1, 2, 4, 5
}
}
3. Labeled Break and Continue
In nested loops (a loop inside another loop), a standard break or continue only affects the innermost loop. If you want to break out of an outer loop from within an inner loop, you must use Labels.
A label is any valid identifier followed by a colon (:).
Example: Labeled Break
public class LabeledBreakExample {
public static void main(String[] args) {
outerLoop: // This is a label
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break outerLoop; // Terminates the OUTER loop completely
}
System.out.println("i=" + i + ", j=" + j);
}
}
System.out.println("Finished!");
}
}
Best Practice Tip
While labeled breaks and continues are powerful, overusing them can make your code resemble "spaghetti code" (similar to the old GOTO statements). Use them sparingly and prefer breaking logic down into separate, smaller methods when nested loops get too complex.