<code>while</code> and <code>do-while</code> Loops in Java

while runs a block while a condition holds — the condition is checked before each iteration, so the body may run zero times. do-while checks after, so the body always runs at least once.

while

while (!queue.isEmpty()) {
    process(queue.poll());
}

do-while

String input;
do {
    input = reader.readLine();
} while (input != null && input.isEmpty());

Infinite loops

while (true) {
    var msg = queue.take();
    if (msg == POISON) break;
    handle(msg);
}

Reading a stream line by line

String line;
while ((line = reader.readLine()) != null) {
    ...
}

The assignment-inside-condition idiom works because assignment expressions evaluate to the value assigned.

Retry with exponential backoff

int attempt = 0;
while (attempt < maxRetries) {
    try {
        call();
        return;
    } catch (TransientException e) {
        Thread.sleep((1L << attempt) * 100);   // 100, 200, 400, 800 ms
        attempt++;
    }
}
throw new MaxRetriesExceeded();

Common mistakes

  • Forgetting to update the condition — infinite loop.
  • Off-by-one between while and do-while — pick the right one by whether the body must run at least once.
  • Busy-waitingwhile (!done) {} pegs a CPU core. Use a proper wait/notify, CountDownLatch or blocking queue.

Related

Pillar: Java control flow. See also for loop, break and continue.