Lesson 17 +10 XP

Break & Continue

Break and Continue

The break and continue statements change how a loop flows.

Break

break stops the loop completely and jumps out of it:

for (int i = 0; i < 10; i++) {
  if (i == 4) {
    break;
  }
  System.out.println(i);
}

This prints 0 1 2 3 and stops when i reaches 4.

Continue

continue skips the current iteration and moves to the next one:

for (int i = 0; i < 10; i++) {
  if (i == 4) {
    continue;
  }
  System.out.println(i);
}

This prints 0 1 2 3 5 6 7 8 9, skipping 4.

Break in a while loop

break also works in while loops:

int i = 0;
while (i < 10) {
  System.out.println(i);
  i++;
  if (i == 4) {
    break;
  }
}

The difference

  • break ends the whole loop.
  • continue ends only the current round and continues with the next.

TL;DR

  • break exits the loop entirely.
  • continue skips the rest of the current iteration.
  • Both work in for and while loops.