Loops normally run until their condition ends them. But sometimes, partway through, you decide you are done early, or that this one item should be skipped. Apex gives you two keywords for exactly that: break and continue.
break ends the loop immediately. No more passes happen, and control jumps to the code after the loop:
for (Integer i = 1; i <= 10; i++) {
if (i == 4) {
break;
}
System.debug(i);
}
// Prints 1, 2, 3 and then stops
Use break when you have found what you were looking for and there is no reason to keep going.
continue skips the rest of the current pass and jumps straight to the next one. The loop does not stop; it just moves on:
for (Integer i = 1; i <= 5; i++) {
if (Math.mod(i, 2) == 0) {
continue;
}
System.debug(i);
}
// Prints 1, 3, 5 (even numbers are skipped)
Use continue when the current item should be ignored but the rest still matter.
The two keywords often appear in the same loop. continue filters out items you do not want, and break stops the whole loop when a signal appears:
for (Integer value : numbers) {
if (value < 0) {
continue; // skip this one
}
if (value == 99) {
break; // stop entirely
}
System.debug(value);
}
break and continue let a loop react to its data instead of blindly running to the end. They keep loop logic flat and readable by handling special cases early.