Beginner 15 min read

While Loops

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

  • Write a while loop with a condition checked before each pass
  • Explain why a while loop needs something inside it that eventually makes the condition false
  • Choose while over for when the number of iterations isn't known in advance

Prerequisites: "Enhanced For Loops"

The shape

Integer stock = 20;

while (stock > 0) {
    stock -= 3;
    System.debug('Stock remaining: ' + stock);
}

Unlike a for loop, there's no built-in counter — you're fully responsible for making sure something inside the loop eventually makes the condition false. Here that's stock -= 3, which shrinks stock toward (and past) zero.

A real business example: Telecom (Call Queue)

Integer callsInQueue = 7;

while (callsInQueue > 0) {
    System.debug('Connecting next caller. Calls remaining: ' + callsInQueue);
    callsInQueue--;
}

System.debug('Queue cleared.');

A call center doesn't know how many calls will be in the queue at any moment — that number changes constantly. while fits this naturally: keep connecting callers as long as there are calls waiting.

Common mistakes

  • Forgetting to change the condition variable inside the loop. If stock was never decremented above, stock > 0 would stay true forever, and Apex would eventually hit a governor limit and throw an error rather than actually loop infinitely.
  • Using while when for fits better. If you already know the exact number of iterations up front, a for loop usually communicates that more clearly than a while loop with a manually managed counter.

Exercise

Declare Integer countdown = 5. Write a while loop that debugs countdown and decreases it by 1 each time, stopping once it reaches 0.

Show hint

while (countdown > 0) { ...; countdown--; }

APEX

While Loops Quiz

1. What must a while loop's body eventually do?

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 while loop keeps running as long as its condition is true, checked fresh before every pass — the right tool when you don't know in advance how many times you'll need to repeat.