Beginner 15 min read

Break and Continue

By the end of this lesson, you'll be able to:

  • Use break to exit a loop early
  • Use continue to skip to the next iteration
  • Explain the difference between the two

Prerequisites: "Do-While Loops"

break: stop the loop entirely

List<Integer> orderIds = new List<Integer>{101, 102, 103, 104, 105};

for (Integer orderId : orderIds) {
    if (orderId == 103) {
        System.debug('Found order 103, stopping search.');
        break;
    }
    System.debug('Checked order ' + orderId);
}

Once orderId == 103, break exits the loop immediately — 104 and 105 are never even checked. This is useful once you've found what you were looking for and don't need to keep going.

continue: skip just this iteration

List<Integer> quantities = new List<Integer>{5, 0, 8, 0, 3};

for (Integer quantity : quantities) {
    if (quantity == 0) {
        continue;
    }
    System.debug('Processing quantity: ' + quantity);
}

continue skips only the rest of the current pass — the loop moves straight on to the next item instead of stopping altogether. Here, every 0 is skipped, but 5, 8, and 3 are still all processed.

A real business example: HR (Candidate Screening)

List<Integer> candidateScores = new List<Integer>{45, 62, 88, 30, 91};

for (Integer score : candidateScores) {
    if (score < 50) {
        continue; // doesn't meet the minimum bar, skip to the next candidate
    }
    if (score >= 90) {
        System.debug('Score ' + score + ' — fast-track to final round.');
        break; // found a top candidate, no need to keep screening
    }
    System.debug('Score ' + score + ' — standard review.');
}

continue filters out candidates who don't clear a minimum bar; break stops screening entirely once a standout is found — both express "change the loop\'s normal path" but in different ways.

Exercise

Given List<Integer> numbers = new List<Integer>{2, 4, 7, 8, 10}, loop through and debug each number, but stop entirely (break) as soon as you hit the first odd number.

Show hint

Use Math.mod(number, 2) != 0 to check for odd, then break.

APEX

Break and Continue Quiz

1. What does continue do?

2. break exits only the current iteration, leaving the loop running.

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

break exits a loop immediately; continue skips the rest of the current iteration and moves to the next one — two ways to override a loop's default "run every pass" behavior.