In Java, break
and continue
are powerful flow control statements used within loops. They allow developers to alter the normal execution of loops, providing greater flexibility in program design.
The break
statement is used to exit a loop prematurely. When encountered, it immediately terminates the loop and transfers control to the next statement after the loop.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
In this example, the loop will print numbers from 0 to 4 and then exit when i
equals 5.
The continue
statement skips the rest of the current iteration and moves to the next iteration of the loop. It's useful when you want to skip specific elements in a loop without terminating it entirely.
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
This code will print only odd numbers between 0 and 9, skipping even numbers.
break
when you need to exit a loop based on a specific condition.continue
to skip iterations that don't meet certain criteria.break
and continue
affect only the innermost loop.Break | Continue |
---|---|
Exits the loop completely | Skips the current iteration |
Execution resumes after the loop | Execution moves to the next iteration |
To fully grasp the power of break
and continue
, it's essential to understand Java's loop structures. Explore Java While Loops and Java For Loops for more context.
Additionally, these statements are often used in conjunction with Java If...Else Statements to create more complex control flows.
Mastering break
and continue
statements in Java enhances your ability to write efficient and flexible code. By controlling loop execution with precision, you can create more responsive and optimized programs.