Break And Continue
break exits the nearest loop. continue skips the rest of the current iteration and begins the next one.
They are useful when a loop reaches a stopping point or finds a value it should ignore, as long as the surrounding loop remains easy to follow.
Stop or skip an iteration
public class Main {
public static void main(String[] args) {
for (int number = 1; number <= 8; number++) {
if (number == 6) {
break;
}
if (number % 2 != 0) {
continue;
}
System.out.println(number);
}
}
}
Output:
2
4
Odd numbers are skipped without printing. When the loop reaches 6, break stops it before 6 can be printed.
Deeply nested control flow with many breaks and continues becomes hard to reason about. Extracting a method can make the rule clearer.
Skip a zero reading and stop at -1. Print each remaining sensor reading.