Labs ICT
โญ Pro Login

Break & Continue

Loops are great, but sometimes you need to interrupt them. Maybe you found what you were looking for and want to stop early. Or maybe you want to skip the current iteration and move on to the next one. That is where break and continue come in.

Break in Loops

The break keyword stops the loop immediately and exits it. No more iterations, the loop is done.

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

This prints 0, 1, 2, 3, 4 and then stops. When i reaches 5, break kicks in and the loop ends. The loop would have gone to 10, but break cut it short.

You see break used a lot when searching. You scan through a list until you find what you need, then stop. No point checking the rest.

Continue in Loops

The continue keyword is different. It does not stop the loop โ€” it just skips the rest of the current iteration and jumps to the next one.

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

This prints 0, 1, 3, 4. Notice that 2 is missing. When i equals 2, the continue statement skips the print and goes straight to the next iteration.

Think of it this way โ€” break slams the door shut, continue just steps aside and lets the next person through.

๐Ÿงช Quick Quiz

What does the continue statement do?