Java Break and Continue
The break and continue keywords in Java are used to control the flow of loops and switch statements. They provide a way to alter the normal execution sequence by either exiting a loop or skipping the current iteration.
break Keyword
The break keyword is used to exit a loop or switch statement prematurely. It immediately terminates the loop or switch and transfers control to the statement following the loop or switch.
Syntax
break;
Example: Using break in a Loop
public class BreakExample {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit loop when i is 5
}
System.out.println(i);
}
}
}
In this example, the break statement is used to exit the loop when i equals 5. As a result, the numbers 0 through 4 are printed.
continue Keyword
The continue keyword is used to skip the current iteration of a loop and proceed to the next iteration. It does not terminate the loop; instead, it causes the loop to jump to the next iteration.
Syntax
continue;
Example: Using continue in a Loop
public class ContinueExample {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i);
}
}
}
Here, the continue statement skips the even numbers in the loop. Only odd numbers from 1 to 9 are printed.
Tips and Best Practices
- Use
breakWisely: Usebreakto exit loops when a certain condition is met, but avoid overusing it as it can make the code harder to read and maintain. continuefor Skipping: Usecontinueto skip unnecessary iterations, especially in loops where certain conditions need to be bypassed.- Nested Loops: In nested loops,
breakandcontinueapply to the innermost loop. Use labeled statements to break or continue outer loops if needed.
outerLoop:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == j) {
continue outerLoop; // Skip to next iteration of outer loop
}
System.out.println("i: " + i + ", j: " + j);
}
}
- Avoid Excessive Use: Excessive use of
breakandcontinuecan lead to complex and less readable code. Consider refactoring loops for clarity.