Course topics

By WebNest Studio Engineering Team

Java - Core Tutorial

Java While and Do-While Loop

while and do-while are Java's two loop constructs built around a single boolean condition rather than the three-part header of a for loop. They are the natural choice when the number of iterations is not known in advance — for example, reading input until a sentinel value appears, or retrying an operation until it succeeds.

The key difference between them is when the condition is checked: while is a pre-test loop that may skip its body entirely, while do-while is a post-test loop that always executes its body at least once, no matter what the condition evaluates to.

Why it matters

Not every loop has a count known in advance. Reading until input ends, retrying until a call succeeds and processing a number digit by digit all depend on a condition, and that is what while and do-while are for. Choosing between them comes down to one question: must the body run at least once?

The while Loop

A while loop checks its condition before every iteration, including the first. If the condition is false from the start, the body never runs at all. This makes while suitable whenever it is genuinely possible that zero iterations are the correct outcome — for instance, processing items in a queue that might already be empty.

The do-while Loop

A do-while loop places its condition check after the body, using the syntax do { ... } while (condition); — note the required semicolon after the closing parenthesis, which is easy to forget since ordinary blocks don't need one. Because the check happens after the body runs, the body is guaranteed to execute at least once even if the condition is false immediately. This matches situations like displaying a menu at least once before deciding whether to repeat it.

Choosing Between while, do-while, and for

Use a for loop when the number of iterations is known or naturally counted. Use a while loop when repetition depends on a condition that might already be false the first time. Use a do-while loop specifically when the body must run at least once regardless of the condition — this is the one behavioral guarantee no other loop form provides.

Watch: How to Choose the Right Java Loop

A quick video on when to reach for for, for-each, while or do-while.

Watch on YouTube

How to Choose the Right Loop

Every Java loop can technically be rewritten as any other, so the choice is not about what is possible — it is about which loop states your intent most clearly and leaves the fewest places for bugs. Ask these questions in order:

  • Do I know how many times it runs? (10 times, once per index, from 1 to n) → use for. The start, stop and step are all visible in one header.
  • Am I visiting every element of an array or collection, without needing the index? → use the for-each loop, for (String s : list). There is no counter at all, so there is no off-by-one bug to write.
  • Am I repeating until something happens, and might it be zero times? (until the number reaches 0, until the queue is empty, until the file ends) → use while.
  • Must the body run once before the condition even makes sense? (show a menu, then ask whether to repeat; read input, then validate it; try once, then decide whether to retry) → use do-while.
  • Does the exit decision happen in the middle of the body? → while (true) with a break at the exit point is clearer than duplicating code before and inside the loop.

A while Loop That Should Have Been a for Loop

A common smell is a while loop that declares a counter above it, tests the counter in the condition, and increments it on the last line of the body. That is a for loop in disguise, and it has two real costs: the counter stays alive after the loop, and the increment sits far from the condition, where it is easy to skip. The classic bug is adding a continue to such a loop — continue jumps straight back to the condition, skipping the increment at the bottom, and the loop never ends. In a for loop, continue still runs the header's update, so the same change is safe.

Examples

A while loop that may not run versus a do-while loop guaranteed to run once

Java
public class LoopComparisonDemo {
    public static void main(String[] args) {
        int count = 5;
        while (count > 0) {
            System.out.println("While count: " + count);
            count--;
        }

        int attempts = 0;
        do {
            System.out.println("Do-while attempt: " + attempts);
            attempts++;
        } while (attempts < 0);
    }
}
Output
While count: 5
While count: 4
While count: 3
While count: 2
While count: 1
Do-while attempt: 0

Choosing the right loop for four common jobs

Java
import java.util.List;

public class ChooseLoopDemo {
    public static void main(String[] args) {
        // 1. Known number of repetitions -> for
        for (int i = 1; i <= 3; i++) {
            System.out.println("for: lap " + i);
        }

        // 2. Every element of a collection, no index needed -> for-each
        List<String> stack = List.of("Java", "Python", "React");
        for (String tech : stack) {
            System.out.println("for-each: " + tech);
        }

        // 3. Repeat until a condition changes, possibly zero times -> while
        int n = 4096;
        int digits = 0;
        while (n > 0) {
            n /= 10;
            digits++;
        }
        System.out.println("while: 4096 has " + digits + " digits");

        // 4. Must run at least once before checking -> do-while
        int[] userInput = {7, 0, 2}; // simulated menu choices; only 1-3 are valid
        int index = 0;
        int choice;
        do {
            choice = userInput[index++];
            System.out.println("do-while: menu shown, user picked " + choice);
        } while (choice < 1 || choice > 3);
    }
}
Output
for: lap 1
for: lap 2
for: lap 3
for-each: Java
for-each: Python
for-each: React
while: 4096 has 4 digits
do-while: menu shown, user picked 7
do-while: menu shown, user picked 0
do-while: menu shown, user picked 2

Why a counting job belongs in a for loop: continue skips a while loop's increment but not a for loop's update

Java
public class ContinueTrapDemo {
    public static void main(String[] args) {
        // for: continue still runs i++, so this safely skips 3
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                continue;
            }
            System.out.print(i + " ");
        }
        System.out.println();

        // while: the same idea needs the increment BEFORE continue.
        // If i++ stayed only at the bottom, i would be stuck at 3 forever.
        int i = 1;
        while (i <= 5) {
            if (i == 3) {
                i++;
                continue;
            }
            System.out.print(i + " ");
            i++;
        }
        System.out.println();
    }
}
Output
1 2 4 5
1 2 4 5

Common Mistakes

  • Using continue in a while loop whose counter is incremented at the bottom of the body — continue skips the increment, so the loop gets stuck on the same value forever.
  • Writing a counted loop as a while loop (counter declared above, incremented at the bottom) when a for loop would keep the start, stop, and step together in one header.
  • Forgetting the semicolon after "while (condition)" in a do-while loop, which is required and causes a compile error if missing.
  • Forgetting to update the variable used in the while condition inside the loop body, creating an accidental infinite loop.
  • Using do-while when the body should not run at all if the condition starts false — do-while always runs its body once, regardless.
  • Confusing the pre-test (while) and post-test (do-while) semantics when the loop body has an observable side effect, like printing or writing to a file.

Exercise

Count how many digits a whole number has by repeatedly dividing it by 10. Make sure the answer for 0 is 1, not 0.

Expected output: 5 for 90210, then 1 for 0.

Java · starter code
public class DigitCount {

    static int countDigits(int n) {
        int count = 0;
        // TODO: divide n by 10 until nothing is left, counting each step
        return count;
    }

    public static void main(String[] args) {
        System.out.println(countDigits(90210));
        System.out.println(countDigits(0));
    }
}
Show hints
  • Each integer division by 10 removes the last digit: 90210 / 10 is 9021.
  • A plain while loop would not run at all for 0. A do-while runs the body once before checking.
Show solution
Java · solution
public class DigitCount {

    static int countDigits(int n) {
        int count = 0;
        do {
            count++;
            n /= 10;
        } while (n != 0);
        return count;
    }

    public static void main(String[] args) {
        System.out.println(countDigits(90210)); // 5
        System.out.println(countDigits(0));     // 1
    }
}

Quick quiz

1. What is the minimum number of times a do-while body runs?

  • A. 1
  • B. 0
  • C. 2
  • D. It depends on the condition
Show answer

A. The condition is checked after the body, so the body always runs at least once.

2. With int i = 5;, how many times does the body of while (i < 5) { ... }</code> run?

  • A. 0
  • B. 1
  • C. 5
  • D. Forever
Show answer

A. A while loop checks the condition first. 5 < 5 is false, so the body never runs.

3. With int i = 0;, what does while (i < 3); { i++; }</code> do?

  • A. Runs the block three times
  • B. Loops forever
  • C. Runs the block once
  • D. Does not compile
Show answer

B. The semicolon after the condition is an empty loop body. i never changes inside that loop, so it never ends, and the block is never reached.

Interview questions

What is the difference between while and do-while?

Show answer

while checks its condition before each iteration, so the body can run zero times. do-while checks after each iteration, so the body runs at least once. Use do-while when the first pass must happen regardless, such as showing a menu before asking whether to continue.

When would you choose a while loop over a for loop?

Show answer

When the number of iterations is not known in advance and the loop is driven by a condition rather than a counter: reading until there is no more input, or retrying until an operation succeeds. When there is a clear counter with a start, an end and a step, a for loop keeps those three parts together and is harder to get wrong.

Key Points to Remember

  • while checks its condition before each iteration and may execute zero times.
  • do-while checks its condition after each iteration and always executes at least once.
  • The do-while syntax requires a trailing semicolon after the while(condition) part.
  • Choose while/do-while over for when the iteration count is not known ahead of time.
  • Quick rule: known count → for; every element → for-each; until something happens (maybe never) → while; at least once → do-while.
  • In a for loop, continue still runs the update expression; in a while loop, continue jumps straight to the condition and skips any increment below it.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs plain Java 17. Frameworks such as Spring, and databases, are not available here. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering