Skip to content
Ameen Abozaid
PublishedBEG-013-L03

while and do-while

  • Lesson 3 of 7
  • 10 min read
  • Beginner
On This Lesson 11 topics

Lesson Overview

A for loop is perfect when you know the number of laps. Often you do not. "Keep asking until the user types a valid number." "Keep saving until the goal is reached." "Keep halving until the piece is small enough." You do not know the count in advance; you know the stopping condition.

In the track picture, a while loop is a run with no lap counter on the starting line: before each lap you ask "is the finish condition met yet?", and you only run if not. A do-while loop is the same run, but you always run one lap first and ask afterwards.

Why this matters: input validation, retries, and "process until the queue is empty" are all unknown-count loops, and they are everywhere in backend code.

This lesson builds on BEG-013-L01 and L02, and on Scanner from BEG-011.

Learning Objectives

By the end of this lesson you will be able to:

  • Write a while loop and say when its condition is checked.
  • Write a do-while loop, including its final semicolon.
  • Explain why while may run zero times and do-while runs at least once.
  • Make sure the body changes something that the condition depends on.
  • Rewrite a counting for loop as a while loop.
  • Choose the right loop for a task and justify the choice.

Written Explanation

The while loop

java
while (condition) {
    // body
}

The condition is checked before each iteration. If it is true, the body runs and the check happens again. If it is false, the loop ends. This means that if the condition is false the first time, the body runs zero times. The Java Tutorials state that while evaluates its expression at the top of the loop.

A while loop has no slot for a start or an update, so you write them yourself:

java
int count = 1;              // start, before the loop
while (count <= 3) {        // condition
    System.out.println(count);
    count++;                // update, inside the body
}

This does exactly what for (int count = 1; count <= 3; count++) does. The difference is where the parts live and what the code tells the reader: for says "counting", while says "until".

The do-while loop

java
do {
    // body
} while (condition);

The body runs first, then the condition is checked. If it is true the loop repeats. The Java Tutorials describe the difference as the condition being evaluated at the bottom instead of the top. So the body always runs at least once.

Notice the semicolon after the closing parenthesis. It is required in do-while and wrong in for and while (L02 showed what a stray semicolon does there).

whiledo-while
Condition checkedBefore the bodyAfter the body
Minimum runs01
Typical use"Until something happens""Ask at least once, then maybe again"

The update is your job

The most common while bug is forgetting that something in the body must change what the condition looks at. Compare:

java
int n = 0;
while (n < 5) {
    System.out.println(n);   // n never changes: infinite loop
}

If the condition is true once and nothing changes the variables it reads, it is true forever. Before you run any while, point to the line that moves the loop toward its end.

Choosing a loop

Ask two questions:

  1. Do I know the number of repetitions before the loop starts? If yes, use for.
  2. If no, must the body run at least once? If yes, use do-while. If it might run zero times, use while.
TaskLoopWhy
Print 1 to 10forKnown count
Read lines until the user types quitwhileUnknown count, may stop immediately
Show a menu, then repeat if the user did not choose Exitdo-whileMust show at least once
Ask for a number between 1 and 10 until validdo-whileMust ask at least once

In practice while is the most common of the two, and any loop can be rewritten as any other. Pick the one that makes the intent obvious.

The infinite loop on purpose

while (true) { ... } is a valid loop that never ends by itself. It is used together with break (next lesson) when the natural place to stop is in the middle of the body. Do not write it by accident: if the condition is meant to be a real condition, make sure it can become false.

Examples

Example 1: halving until small (simple)

How many times can you halve 100 (integer division) before it reaches 1?

java
int size = 100;
int steps = 0;
while (size > 1) {
    size = size / 2;
    steps++;
}
System.out.println("Halved " + steps + " times, size=" + size);

Output:

text
Halved 6 times, size=1

The values are 100, 50, 25, 12, 6, 3, 1: six divisions (25 / 2 is 12 because integer division drops the fraction, as you learned in BEG-010-L01). We could not have written this as a counting for without first working out the answer. The count is a result, not an input.

And a while whose condition is false at the start:

java
int zero = 0;
while (zero > 5) {
    System.out.println("never");
}

It prints nothing. The body ran zero times.

Example 2: ask until valid (practical)

java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n;
        do {
            System.out.print("Enter 1-10: ");
            n = scanner.nextInt();
        } while (n < 1 || n > 10);
        System.out.println("Got " + n);
    }
}

Run with the three inputs 0, 15, and 7 typed one per line, the console shows (here the typed text is not echoed, because the input came from a file; on a real keyboard you will see what you type):

text
Enter 1-10: Enter 1-10: Enter 1-10: Got 7

The prompt appears three times: 0 and 15 were rejected and 7 was accepted. A do-while is the natural fit because we cannot check n before we have asked for it once. Declaring n before the do matters: a variable declared inside the braces would not be visible in the condition after them.

This version still crashes if the user types a word instead of a number; BEG-011-L05 and the guessing game in L07 show how to guard against that.

Example 3: saving toward a goal (realistic)

A user has 200 saved and adds 75 each month. How many months until they have at least 500?

java
double savings = 200;
int months = 0;
while (savings < 500) {
    savings += 75;
    months++;
}
System.out.println(months + " months, savings " + savings);

Output:

text
4 months, savings 500.0

The loop ends when the condition savings < 500 becomes false, which happens exactly when savings reaches 500. If the monthly amount were 0, the loop would never end: the condition would stay true forever. Real code often adds a safety limit for that reason.

Backend Insight

Unknown-count loops are the backbone of servers:

  • A server's main loop is conceptually while (running) { wait for a request; handle it; }.
  • Retry logic is while (not succeeded and attempts < limit). Note the limit: retrying forever against a service that is down is an outage you caused.
  • Input validation, as in Example 2, is a do-while or while loop: ask again until the data is acceptable.

The habit to build: every while loop needs a reason to end that you can state in one sentence, and ideally a safety limit when the outside world is involved.

Common Mistakes

Mistake 1: Forgetting to update the condition variable

  • Incorrect: while (i < 10) { System.out.println(i); }
  • Correct: add i++; inside the body.

Mistake 2: Missing semicolon after do-while

java
do {
    n++;
} while (n < 5)      // compile error: ';' expected

Mistake 3: Declaring the variable inside a do block

A variable declared inside the braces of the do is out of scope in the while (...) condition. Declare it before the do.

Mistake 4: Using while when the body must run first

If the condition reads a value you only get inside the loop, a while would read it before it exists. Use do-while, or read once before the loop and again at the end.

Mistake 5: Putting a semicolon after while (condition)

while (n < 5); is a loop with an empty body. If n is not changed, it runs forever.

Exercises

Try each exercise yourself before opening the solutions.

Level A: Foundation

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

Show solution A1

A1. while: 0 times. do-while: 1 time.

A2. What does this print?

java
int x = 3;
while (x > 0) {
    System.out.print(x + " ");
    x--;
}
Show solution A2

A2. 3 2 1 (all on one line, with trailing space).

A3. What is wrong with do { x++; } while (x < 3)?

Show solution A3

A3. The final semicolon after the while (...) is missing.

Level B: Application

B1. Rewrite for (int i = 1; i <= 4; i++) { System.out.println(i); } as a while loop.

Show solution B1

B1.

java
int i = 1;
while (i <= 4) {
    System.out.println(i);
    i++;
}

B2. Write a loop that doubles a number starting at 1 and prints each value until it exceeds 100. Which loop did you use and why?

Show solution B2

B2.

java
int v = 1;
while (v <= 100) {
    System.out.println(v);
    v *= 2;
}

It prints 1, 2, 4, 8, 16, 32, 64. The loop stops when v becomes 128. A while fits because the stop is a condition on the value, not a count (a for with a known count would also work once you computed the 7).

B3. For each task pick for, while, or do-while: (a) print the numbers 1 to 20; (b) keep reading words until the user types stop; (c) show a "Retry? (y/n)" prompt after every attempt.

Show solution B3

B3. (a) for: known count. (b) while: unknown count, may stop at once. (c) do-while: the prompt must appear at least once.

Level C: Challenge

C1. A tank holds 1000 litres and loses 12 percent of its content each hour (integer arithmetic: level = level - level * 12 / 100). Count how many hours until it holds fewer than 100 litres.

Show solution C1

C1.

java
int level = 1000;
int hours = 0;
while (level >= 100) {
    level = level - level * 12 / 100;
    hours++;
}
System.out.println(hours);

It prints 19. The levels are 880, 775, 682, 601, 529, 466, 411, 362, 319, 281, 248, 219, 193, 170, 150, 132, 117, 103, then 91, which is below 100. Integer division matters: 880 loses 105, not 105.6.

C2. Explain why this loop never ends and give two different fixes:

java
int tries = 0;
while (tries < 3) {
    System.out.println("Trying");
}
Show solution C2

C2. tries never changes, so tries < 3 stays true. Fix 1: add tries++; in the body. Fix 2: turn it into for (int tries = 0; tries < 3; tries++).

Mini Challenge

Write a "minimum password length" checker using hard-coded sample passwords (to avoid keyboard input for now) or Scanner if you prefer:

  1. Use a loop that keeps asking for a password until it has at least 8 characters (password.length() from BEG-009-L03 gives the length).
  2. After a valid password is accepted, print how many attempts it took.

Check your work: you used a loop that runs at least once, you counted attempts with a variable declared before the loop, and a password of 8 or more characters ends the loop.

Summary & Next Lesson

Key takeaways

  • while (condition) checks first, so it can run zero times.
  • do { } while (condition); runs first, then checks, so it runs at least once; the semicolon is required.
  • Something in the body must move the loop toward its end.
  • Use for for known counts, while for "until", and do-while when the body must run once.
  • Variables used in the condition must be declared before the loop.

Next lesson

The next lesson, "break, continue, and loop control", shows how to leave a loop early or skip one iteration on purpose.

Self-check

  1. Which loop can run zero times?
  2. Which loop needs a semicolon after its condition?
  3. Which loop do you use to ask for input at least once?
  4. What makes while (n < 5) { print(n); } infinite?
  5. Why must n be declared before a do block that uses it in while (n < 1)?
Show answers
  1. while (and for).
  2. do-while.
  3. do-while.
  4. n is never changed in the body, so the condition never becomes false.
  5. A variable declared inside the braces is not visible in the condition after them.

References

  • Oracle, The while and do-while Statements (Java Tutorials). It supports that while evaluates its expression at the top of the loop, that do-while evaluates it at the bottom, and that while (true) is an infinite loop.
  • Oracle, Java Language Specification, SE 21, Chapter 14. It supports that a while body runs zero times when the condition is false at first and that a do body always runs once. Examples 1 to 3 were compiled and run with JDK 21. The B2 and C1 solutions were also compiled and run.

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.