do while and while Loop in Java: Syntax, Examples, and Differences
-
Last Updated: October 16, 2023
-
By: javahandson
-
Series
Learn Java in a easy way
This guide covers the do while and while loop in Java, two of the first loops you will learn. A do while loop runs a block of code first and checks the condition afterward. That small twist makes it perfect for menus, input checks, and any task that must run at least once. In this guide we build the idea from scratch, compare the two loops, and walk through real programs. If you want more Java topics, open the Java topics menu.
Loops let you repeat work without copying code. You write the steps once, and Java runs them again and again. The do while loop in Java is one of three loop styles you will meet early, alongside the while loop and the for loop.
What sets this loop apart is its timing. It runs the body first, then it looks at the condition. So the body always runs at least one time, even when the condition is false from the very start.
Think about an ATM. It shows you the menu, then asks if you want another transaction. The menu has to appear once before any question makes sense. That “act first, ask later” flow is exactly what a do…while loop gives you.
This pattern shows up all over real code. Menus use it. Input prompts use it. Retry loops that must try once before giving up use it too. Once you spot the shape, you will reach for it often.
We start simple and build up slowly. Here is the plan for the rest of the article:
You do not need much to follow along. If you can write a basic Java class with a main method, you are ready. We keep every example small and explain each one in plain words.
A do…while loop repeats a block of statements as long as a condition stays true. The catch is the order. It runs the block first, then it tests the condition to decide whether to go around again.
Picture tasting a pot of soup while you cook. You take a sip, then you ask, “Does it need more salt?” If the answer is yes, you add salt and taste again. You never skip that first sip.
The sip is the loop body. The question is the condition. Because you taste before you ask, you always taste at least once. That is the heart of a do…while loop.
A plain while loop flips the order. It asks the question first, then acts. So sometimes it never acts at all. We will see that contrast clearly in a moment.
The shape of a do…while loop is short. You write do, then the body in braces, then while with the condition. One detail matters: a semicolon closes the whole thing.
do {
// execute a set of statements
} while (condition);That trailing semicolon after the condition is required. Miss it, and the code will not compile. We call this out again in the mistakes section because it is easy to forget.
If the body holds only one statement, the braces are optional. Still, most developers keep the braces anyway. They make the loop easier to read and safer to edit later.
The loop follows the same rhythm every time. Here is the exact order Java uses:
do block once.while line and evaluate the condition.Notice where the check lives. It sits at the bottom, not the top. That single fact explains everything special about this loop.
Enough theory. Let us write a real program and watch it run. We will print the numbers 1 through 5.
This version uses braces because the body has two statements. We print the counter, then we bump it up by one.
package com.java.handson.control.statements;
public class Test {
public static void main(String[] args) {
int counter = 1;
do {
System.out.println(counter);
counter++;
} while (counter <= 5);
}
}
// Output:
// 1
// 2
// 3
// 4
// 5Run it, and five lines appear. The loop printed 1, then climbed to 5, then stopped. Let us trace exactly how it got there.
Following the counter by hand makes the flow click. Here is each pass through the loop:
counter to 1 before the loop starts.counter becomes 2. Now the while test runs.counter reaches 5 and prints it.counter becomes 6. Now 6 <= 5 is false, so the loop ends.See the pattern? The very first print happened before any test. That is the do…while promise in action. The body ran once no matter what.
When the body is a single line, you may drop the braces. Here we print and increment in the same statement with counter++.
package com.java.handson.control.statements;
public class Test {
public static void main(String[] args) {
int counter = 1;
do
System.out.println(counter++);
while (counter <= 5);
}
}
// Output:
// 1
// 2
// 3
// 4
// 5The output is identical. Both versions print 1 to 5. The braces just make room for more statements when you need them.
Our advice? Keep the braces even for one line. The day you add a second statement, braces save you from a sneaky bug. That habit costs nothing and prevents real headaches.
The while loop is the do…while loop’s close cousin. It repeats a block as long as a condition holds true. The one difference is when it checks that condition.
A while loop puts the condition right at the top, inside the parentheses. The body follows in braces. There is no trailing semicolon here.
while (condition) {
// execute a set of statements
}Read it out loud: “while this condition is true, keep doing this.” The check comes before the body, so the loop tests the water before it jumps in.
As with do…while, a single-statement body can skip the braces. And as before, keeping the braces is the safer habit.
Here is the same counting task, now written as a while loop. Compare it with the do…while version above.
package com.java.handson.control.statements;
public class Test {
public static void main(String[] args) {
int counter = 1;
while (counter <= 5) {
System.out.println(counter);
counter++;
}
}
}
// Output:
// 1
// 2
// 3
// 4
// 5Same output, 1 through 5. The logic reads almost the same. The only real change is that the test now guards the very first entry into the body.
Now for the moment that shows the true gap between these loops. What if the condition is false before we even begin? Watch the while loop here.
int counter = 10;
while (counter <= 5) {
System.out.println(counter);
counter++;
}
System.out.println("Loop finished");
// Output:
// Loop finishedThe loop printed nothing. Since 10 <= 5 is false from the start, the body never ran once. The while loop checked first, saw a false condition, and skipped straight past.
Hold that result in mind. In the next section we run the exact same setup as a do…while loop. The outcome will surprise you if you are new to this.
People often ask which loop to pick. The honest answer is that they are nearly the same. Only the timing of the condition check sets them apart.
A while loop uses an entry check. It tests the condition at the top, before the body. So the body might run zero times.
A do…while loop uses an exit check. It tests the condition at the bottom, after the body. So the body always runs at least once.
That is the whole story. Everything else about these two loops is identical. Same variables, same conditions, same break and continue rules.
This table lines up the two loops so you can see the trade-offs at a glance.
| Aspect | do…while loop | while loop |
|---|---|---|
| Condition check | After the body (bottom) | Before the body (top) |
| Minimum runs | Always runs at least once | May run zero times |
| Loop type | Exit-controlled | Entry-controlled |
| Trailing semicolon | Required after while |
Not used |
| Best fit | Menus, prompts, retries | Guarded loops, unknown counts |
Neither loop is faster than the other. They compile down to nearly the same instructions. You pick one based on whether the body must run once, not on speed.
Remember the while loop that printed nothing? Here is the same false condition, now inside a do…while loop.
int counter = 10;
do {
System.out.println(counter);
counter++;
} while (counter <= 5);
System.out.println("Loop finished");
// Output:
// 10
// Loop finishedThis time the loop printed 10. The body ran before any check, so it fired once. Then the test found 11 <= 5 false and stopped the loop.
There it is, side by side. The while loop printed nothing; the do…while loop printed 10. When the body must run at least once, do…while is your tool.
The “run once, then check” pattern is not just a textbook trick. It solves everyday problems cleanly. Let us look at three common ones.
A menu has to show up before you can pick anything. So you display it, read a choice, and repeat until the user quits. A do…while loop fits this like a glove.
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Exit");
choice = sc.nextInt();
if (choice == 1) System.out.println("Money deposited");
else if (choice == 2) System.out.println("Money withdrawn");
} while (choice != 3);
System.out.println("Goodbye");The menu appears at least once, which is exactly what you want. The loop keeps looping until the user types 3. A while loop could do this too, but you would have to show the menu once by hand before the loop.
Say you want a number between 1 and 10. You must ask once, then keep asking until the answer is valid. Again, the body runs before the check.
Scanner sc = new Scanner(System.in);
int age;
do {
System.out.println("Enter age (1-120): ");
age = sc.nextInt();
} while (age < 1 || age > 120);
System.out.println("You entered: " + age);The prompt shows every time the input is wrong. Type -5, and the loop asks again. Type 25, and the condition turns false, so the loop lets you through.
Some tasks need at least one attempt before you know if they worked. A login prompt is a classic case. You try once, and you retry only if it fails.
Reading a file, connecting to a server, or rolling a dice all share this shape. Do the thing, then decide whether to repeat. The do…while loop maps onto that idea with no extra code before the loop.
Could you write these tasks with a while loop instead? Sure. You would just move the first attempt above the loop and repeat the code. The do…while loop spares you that duplication, which keeps the logic in one place.
Two keywords give you finer control inside any loop. They work in do…while loops just as they do in while and for loops.
The break keyword leaves the loop right away. It does not finish the current pass or check the condition. It just jumps out.
int counter = 1;
do {
if (counter == 3) {
break; // leave the loop at 3
}
System.out.println(counter);
counter++;
} while (counter <= 5);
// Output:
// 1
// 2The loop printed 1 and 2, then hit the break at 3 and quit. Numbers 3, 4, and 5 never printed. Use break when you find what you were looking for and want to stop early.
The continue keyword skips the rest of the current pass. It then jumps to the condition check. Be careful, though, since a bad skip can cause an endless loop.
int counter = 0;
do {
counter++;
if (counter == 3) {
continue; // skip printing 3
}
System.out.println(counter);
} while (counter <= 5);
// Output:
// 1
// 2
// 4
// 5
// 6Notice how 3 is missing from the output. When counter hit 3, continue skipped the print line. Since we increment at the top of the body, the counter still moved forward, so the loop stayed safe.
A few traps catch beginners over and over. Let us name each one so you can dodge it.
The do…while loop ends with a semicolon after the condition. Leave it out, and the compiler complains right away. This is the most common slip with this loop.
// Wrong - missing semicolon
do {
System.out.println(counter++);
} while (counter <= 5) // compile error!
// Correct
do {
System.out.println(counter++);
} while (counter <= 5);Train your eyes to spot it. Every do…while loop needs that closing semicolon. The plain while loop does not, which is why the mix-up happens.
A loop runs forever when the condition never turns false. Usually this means you forgot to update the variable the condition depends on.
int counter = 1;
do {
System.out.println(counter);
// oops - we never do counter++
} while (counter <= 5);
// prints 1 foreverHere the counter stays at 1, so 1 <= 5 is always true. The fix is simple: make sure something in the body moves the condition toward false. Always give your loop a way to end.
Getting the loop to run one time too many or too few is a classic bug. It usually comes from a wrong comparison, like < where you meant <=.
Test the edges by hand. Ask what the counter is on the first pass and the last pass. Walking those two cases catches most off-by-one slips before they ship.
Put your loop variable inside the body, and it resets on every pass. That gives you another endless loop, since the counter never grows past its start value.
// Wrong - counter resets each pass
do {
int counter = 1;
System.out.println(counter);
counter++;
} while (counter <= 5); // counter not visible here anywayDeclare the counter before the loop instead. That way it keeps its value across passes, and the condition can actually reach false.
Let us tie the ideas together with one small program. We will build a tiny number guessing game.
The computer holds a secret number. The player guesses until they get it right. A do…while loop fits because the player must guess at least once.
import java.util.Scanner;
public class GuessGame {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int secret = 7;
int guess;
do {
System.out.println("Guess the number (1-10): ");
guess = sc.nextInt();
if (guess > secret) {
System.out.println("Too high");
} else if (guess < secret) {
System.out.println("Too low");
}
} while (guess != secret);
System.out.println("Correct! The number was " + secret);
}
}The secret is 7. The player keeps guessing while the guess is wrong. Each pass gives a hint, “Too high” or “Too low”, to steer the next try.
Follow one sample run to see the loop breathe. Suppose the player types 5, then 9, then 7:
This is the do…while loop at its best. The prompt had to appear before the first guess, so an exit-checked loop was the natural choice. The player always plays at least one round.
A: A do…while loop repeats a block of statements as long as a condition stays true. It runs the body first and checks the condition afterward. Because of that order, the body always runs at least once, even when the condition is false from the start.
A: A while loop checks the condition before the body, so it may run zero times. A do…while loop checks after the body, so it always runs at least once. We call while an entry-controlled loop and do…while an exit-controlled loop.
A: Yes. The loop runs the body before it ever tests the condition. So even if the condition is false on the first check, the body has already run one time. This is the main reason to choose a do…while loop.
A: The while line with its condition is a full statement that closes the loop, so Java requires a semicolon after it. Leaving it out causes a compile error. A plain while loop does not need this semicolon, which is why beginners often mix the two up.
A: Reach for a do…while loop when the body must run at least once. Menus, input prompts, and retry logic all fit this pattern. If the body might need to run zero times, a while loop is the better choice.
A: No. Both loops compile to almost the same instructions, so speed is not a reason to prefer one. You choose between them based on whether the body must run at least once, not on performance.
A: Yes. If nothing in the body moves the condition toward false, the loop never stops. The usual cause is forgetting to update the counter. Always make sure the body changes the variable the condition depends on.
A: Yes. The break keyword exits the loop right away, and continue skips the rest of the current pass and jumps to the condition check. Both work the same way in do…while, while, and for loops.
A: You can skip the braces when the body is a single statement. Most developers keep the braces anyway. They make the loop clearer and prevent bugs when you later add a second statement.
A: Java supports the for loop, the while loop, the do…while loop, and the enhanced for-each loop. The for loop suits a known count, while and do…while suit unknown counts, and for-each walks over arrays and collections.
Let us wrap up what we covered. A do…while loop repeats a block as long as its condition stays true, and it checks that condition at the bottom.
Because the check comes last, the body always runs at least once. That single trait makes the loop perfect for menus, input prompts, and retries. Just remember the trailing semicolon after the condition.
The while loop is its mirror image. It checks first, so its body may run zero times. Neither loop is faster, so you pick based on whether the body must run once.
One more tip before you go. When you meet a new loop, trace it on paper with a small input. Write down the counter after each pass, and note when the condition flips to false. That habit turns confusing loops into clear ones.
Try the examples yourself. Change the numbers, break early, and skip a value. Playing with real code is the fastest way to make these loops second nature.