How do break and continue differ in Java, and what happens when they appear inside a nested loop?
Both of them change the flow of the loop that they sit inside, but they do opposite things.
The statement break leaves the loop completely. The code after the loop carries on as normal.
The statement continue skips the rest of this round and goes back to the top of the loop. The loop then runs the next round, if there is one.
public class Main {
public static void main(String[] args) {
// break leaves the loop early.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
System.out.println("break at " + i);
break;
}
System.out.println("break loop : " + i);
}
// continue skips the rest of this round.
for (int i = 1; i <= 5; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println("continue loop : " + i);
}
}
}
Here is what happens when they are inside a nested loop. A break only leaves the innermost loop that contains it. The outer loop carries on with its next round. A continue behaves the same way, and it only affects the innermost loop as well.
That is almost always what you want, but it is also the reason that a nested loop sometimes keeps going when you expected it to stop. When you want to leave all of the loops at once, you need a label, and that is what the next question is about.
The final question in this topic looks at the cleanest way to get out of several loops at once.