Beginner 15 min read

Do-While Loops

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

  • Write a do-while loop
  • Explain the one real difference between while and do-while
  • Identify a situation where "run at least once" matters

Prerequisites: "While Loops"

The shape

Integer attempts = 0;

do {
    attempts++;
    System.debug('Attempt number ' + attempts);
} while (attempts < 3);

Notice the condition comes after the body here, not before. This means the body always runs at least once, even if the condition would have been false from the very start.

The one real difference from while

Integer x = 10;

while (x < 5) {
    System.debug('This never runs.');
}

do {
    System.debug('This runs exactly once.');
} while (x < 5);

A while loop checks first, so if the condition starts false, the body never executes at all. A do-while loop always runs the body once, checking only afterward — that's the entire distinction.

A real business example: Utilities (Meter Reading Retry)

Integer attempt = 0;
Boolean readingReceived = false;

do {
    attempt++;
    System.debug('Attempting to read smart meter, try #' + attempt);
    // in real code: readingReceived would be set based on an actual API response
} while (! readingReceived && attempt < 3);

A retry loop is the classic case for do-while: you always want to attempt the read at least once before deciding whether to retry — checking "should I retry?" before the first attempt wouldn't make sense.

Exercise

Write a do-while loop that debugs "Trying..." and increments an Integer tries starting at 0, stopping once tries reaches 1. Confirm the body still runs even though the loop only executes once.

Show hint

do { tries++; System.debug('Trying...'); } while (tries < 1);

APEX

Do-While Loops Quiz

1. What is guaranteed about a do-while loop's body?

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

A do-while loop is a while loop that checks its condition after the first pass instead of before — guaranteeing the body runs at least once no matter what.