Skip to main content
Advertisement

4.3 Control Flow Statements

To better regulate loops, Java provides special keywords allowing direct intervention in the control flow. By utilizing these control variables, break and continue, you can dynamically manage the iterations.

1. The break Statement

When a break statement is declared, it completely exits the innermost loop enclosing it.(Also used in switch statements).

It is predominantly used within infinite loops (while(true)) to forcefully exit the loop when a specific condition is met.

int sum = 0, i = 0;

while(true) {
if (sum > 100) {
break; // Force-exits the loop when the sum exceeds 100
}
i++;
sum += i;
}
System.out.println("Value of i when the sum exceeds 100 = " + i);

2. The continue Statement

Upon encountering a continue statement, all subsequent portions of the current iterative cycle are skipped, and it directly moves to the end of the block to "continue" to the "next iteration stage".

Unlike break, it distinguishes itself by not exiting the loop itself.

for (int i = 0; i <= 10; i++) {
if (i % 3 == 0) {
continue; // If it's a multiple of 3, skip the print below and directly advance to the loop's next stage (the increment formula behaves safely)
}
System.out.println(i); // Consequently, 3, 6, 9 are not printed.
}

Thus, it keeps your if statements very clean when organizing skips over certain iteration logic during the whole loop operation.

Advertisement