PartRole
doStarts the loop; the body follows immediately
{ body }The statements to repeat; must update the state the condition reads
while (condition)A boolean expression checked after each pass
;Ends the whole do-while statement; leaving it out is a compile error

Why the semicolon? The entire do { … } while (…) is a single statement, and Java statements end with ;. A plain while has no semicolon after its condition, because its body comes after the condition.

How Does a Do-While Loop Work in Java?

Whiteboard
Loading diagram...

There is no path from Start to Exit that skips the body. The condition sits after the body, which is why one pass is guaranteed.

Steps:

  1. Java enters the body without checking anything.
  2. The body runs, including the update.
  3. The condition is evaluated.
  4. If true, go back to step 2; if false, leave the loop.

Do-While Loop Examples in Java

Example 1: A Basic Counter

Code (Java 21):

Output:

Round 1 startedRound 2 started
Round 3 started
Game over

Dry Run of Example 1

Passround at startBody printsround after ++Check round <= 3
11Round 1 started2true → repeat
22Round 2 started3true → repeat
33Round 3 started4false → exit

The body ran 3 times and the condition was checked 3 times. In a do-while the number of checks equals the number of passes. In a while loop there is one extra check at the start.

Example 2: The Condition Is False From the Start

Code (Java 21):

Output:

Current level: 10Final level: 11

10 < 5 was false all along, yet the body ran once and even changed level. That is the defining behaviour of a do-while loop, and it can be a feature or a bug depending on what the body does.

Example 3: Counting Digits Correctly, Including 0

Here the guaranteed first pass fixes a real bug. The number 0 has one digit, but a while loop counts zero:

Code (Java 21):

Output:

4072 -> while: 4, do-while: 47 -> while: 1, do-while: 1
0 -> while: 0, do-while: 1

For 0, the while loop never enters, so it counts 0 digits. The do-while counts the one digit before checking, which is correct. (The outer for (int number : numbers) is a for-each loop; it simply visits each number.)

Do-While vs While Loop in Java

Run both loops with the same condition and the same starting value:

Code (Java 21):

Output:

do-while: charging...battery = 110

The battery was already full. The while loop correctly did nothing; the do-while charged once anyway.

Whiteboard
Loading diagram...

The only difference is where the test sits. That position decides whether the body can be skipped.

Featurewhiledo-while
TypeEntry-controlled (pre-test)Exit-controlled (post-test)
Condition checkedBefore each passAfter each pass
Minimum runs01
Semicolon after while (...)NoYes, required
Condition checks for n passesn + 1n
Best whenThe value to test already existsThe body produces the value to test
Typical useSentinel input, queues, digit loopsMenus, input validation, games, retries

Rule of thumb: if the body must run to create the value you test (a user’s choice, a dice roll, an input), use do-while. If the value already exists and the action should happen only when needed, use while.

Writing a Do-While as a While Loop

Any do-while can be rewritten as a while loop, but you need either a duplicated first pass or a flag:

Code (Java 21):

Output:

5 4 (do-while)5 4 (while with a flag)

Both work, but the do-while says “run once, then maybe repeat” without the extra flag.

Input Validation Using Do-While Loop With Scanner

Validation is the textbook do-while case: you must read a value before you can check it.

Code (Java 21):

Sample run (the user typed six, 9, 4):

Rate this lesson (1-5): sixPlease type a number (1-5): 9
Rate this lesson (1-5): 4
Thanks! You rated 4/5

How it works:

  • rating needs no dummy starting value, because the body assigns it before the condition reads it. Compare this with the -1 trick needed in the while loop lesson.
  • The inner while (!in.hasNextInt()) rejects text like “six” without crashing; in.next() discards it.
  • The outer condition rejects numbers outside 1–5, such as 9, and asks again.

Menu-Driven Program Using Do-While in Java

A menu must appear at least once, and it repeats until the user picks Exit. This is a natural fit for do-while.

Code (Java 21):

Sample run (the user typed 1, 10, 2, 37, 5, 0):

1. km to miles  2. Celsius to Fahrenheit  0. ExitChoice: 1
Kilometres: 10
10.00 km = 6.21 miles
1. km to miles 2. Celsius to Fahrenheit 0. Exit
Choice: 2
Celsius: 37
37.0 C = 98.6 F
1. km to miles 2. Celsius to Fahrenheit 0. Exit
Choice: 5
Invalid choice
1. km to miles 2. Celsius to Fahrenheit 0. Exit
Choice: 0
Converter closed

choice is declared before do so the condition can see it (see Mistake 2). With a plain while loop you would have to print the menu before the loop and again inside it.

Retry Until Success (With a Limit)

“Try, then check whether to try again” is another do-while shape. Always add a maximum, so repeated failure can’t loop forever.

Code (Java 21):

Output:

Roll 1: 5Roll 2: 3
Roll 3: 4
Roll 4: 5
Roll 5: 5
Roll 6: 5
Roll 7: 5
Roll 8: 6
Got a six in 8 rolls

The condition has two exits joined by &&: success (roll == 6) or running out of attempts. The fixed seed 7 makes this demo print the same rolls every time. Remove the seed (new Random()) for real randomness.

Infinite Do-While Loop in Java

do { … } while (true); never ends on its own; you need break (or return) inside the body.

Code (Java 21):

Output:

 Reached 1 after 6 divisions

while (true) { … } and do { … } while (true); behave the same, since the first check of true can never fail. Most developers write while (true). You’ll learn break fully in Break and Continue in Java.

Common Mistakes With Do-While Loops in Java

Mistake 1: Forgetting the Semicolon After while (condition)

Wrong:

Compiler output (Java 21):

MissingSemicolon.java:7: error: ';' expected        } while (i <= 3)
^
1 error

Fix: } while (i <= 3);. Remember: semicolon after a do-while condition, never after a plain while condition.

Mistake 2: Declaring the Loop Variable Inside the Body

Wrong:

Compiler output (Java 21):

ScopeTrap.java:6: error: cannot find symbol        } while (roll != 6);
^
symbol: variable roll
location: class ScopeTrap
1 error

Why: the body { … } is a block, and roll dies at its closing brace. The condition sits outside that block. Fix: declare it before do (int roll;) and assign it inside, as the menu and dice examples do.

Mistake 3: The “Already Valid” Trap

Wrong tool for the job:

Code (Java 21):

Output:

do-while: Low stock alert! Ordering more...Stock after do-while: 45
Stock after while: 25

Stock was healthy, yet the do-while raised a false alarm and placed an order. When the body has side effects (ordering, charging, sending a message), a guaranteed first run can be a real bug. Fix: use while whenever the value you test already exists.

Mistake 4: A Condition That Never Becomes False

If the body never moves the condition toward false, a do-while runs forever, just like a while loop. For example, do { System.out.println(n); } while (n < 5); never changes n. Make sure every pass updates the tested variable, and give retry loops a maximum attempt count.

Mistake 5: Assuming nextInt() Is Safe

in.nextInt() throws InputMismatchException when the user types text. Guard it with hasNextInt(), as in the rating example, whenever input comes from a person.

Best Practices

  1. Choose do-while only when the first pass is always correct, even if the condition would be false.
  2. Declare the variables the condition uses before do.
  3. Put while (condition); on the same line as the closing brace (} while (...);), so the semicolon is easy to spot and nobody mistakes it for a separate while loop.
  4. Keep the condition simple and meaningful: while (choice != 0) reads better than a tangle of flags.
  5. Give every retry loop a maximum attempt count.
  6. Validate input types with hasNextInt() / hasNextDouble().
  7. Avoid side effects that are harmful when repeated once unnecessarily, or use while instead.
  8. Always use braces, even for a one-statement body.

Real-World Example: Number Guessing Game

Games are a natural do-while case: the player must guess before you can compare.

Code (Java 21):

Sample run (the user typed 50, 25, 37):

Guess the number (1-100): 50Too high
Guess the number (1-100): 25
Too low
Guess the number (1-100): 37
Correct! You needed 3 tries.

The secret is fixed so the demo is repeatable; in a real game you would use new Random().nextInt(100) + 1.

Where you’ll see do-while in practice: console menus (ATM, billing, library systems), “Play again? (y/n)” prompts, input validation forms in CLI tools, and retry-with-limit logic for network calls or OTPs.

Practice Problems

  1. Easy: Print numbers from 10 down to 1 using a do-while loop. Hint: start at 10, decrement, condition n >= 1.
  2. Easy: Find the sum of digits of a number (e.g., 9045 → 18). Make sure 0 gives 0. Hint: Example 3’s pattern.
  3. Easy–Medium: Keep asking for a password until its length is at least 8. Hint: in.next().length().
  4. Medium: Build a “Play again? (y/n)” loop around a simple task, stopping when the user types n. Hint: read a String and compare with .equals("n").
  5. Medium: Write a simple calculator menu (add, subtract, multiply, divide, exit) that refuses to divide by zero. Hint: combine the menu pattern with an if check.

Run your answers in the ExamAdda online compiler.

Interview Questions on Do-While Loop in Java

1. What is the main difference between while and do-while?
while checks the condition before the body and can run 0 times; do-while checks after the body and runs at least once.

2. Why is a semicolon needed after while (condition) in a do-while?
Because the whole do { } while ( ) is one statement, and Java statements end with ;. Without it you get “‘;’ expected”.

3. Is do-while entry-controlled or exit-controlled?
Exit-controlled (post-test). It is the only exit-controlled loop in Java.

4. Output of: int x = 5; do { System.out.print(x); x++; } while (x < 3);?
It prints 5. The body runs once before 6 < 3 is checked and found false.

5. Can a variable declared inside the do block be used in the condition?
No. Its scope ends at the closing brace, so the compiler reports “cannot find symbol”. Declare it before do.

6. When should you NOT use a do-while?
When the value to check already exists and the body has side effects, such as sending an alert or charging a payment. A guaranteed first run would do the wrong thing.

7. How do you prevent an infinite retry loop?
Add an attempt counter to the condition, e.g. while (!success && attempts < MAX).

8. Can every do-while loop be rewritten as a while loop?
Yes, by duplicating the body once before the loop or by using a firstPass flag. Do-while simply expresses “run once, then maybe repeat” more directly.

Article Summary

  • A do-while loop runs its body first and checks the condition afterwards, so it always executes at least once.
  • Its syntax ends with while (condition);, and the semicolon is mandatory.
  • Variables used in the condition must be declared before do, not inside the body.
  • It fits input validation, menus, games, and retries; use a limit for retries.
  • Use while instead when the value already exists and an unneeded first run would cause side effects.

Conclusion

The do-while loop is the right choice whenever “do it once, then decide” describes your logic. Before choosing it, ask one question: is the first run always correct? If yes, do-while gives cleaner code than a while loop with a dummy value or flag. If not, stay with while. Next, learn how to leave a loop early or skip a pass in the Break and Continue in Java lesson, and test yourself with ExamAdda practice questions.

Previous lesson: While Loop in Java
Next lesson: Break and Continue in Java

References