Do While Loop in Java
The do-while loop is an exit-controlled loop — the body runs at least once before the condition is checked. It is perfect for menu programs, retry prompts and any code that must execute at least one time regardless of the condition.
Key Features
Post-Test
Condition is checked after the loop body.
Always Runs Once
The body executes at least one time.
Menu Programs
Ideal for choice-based menus that loop until the user exits.
Retry Pattern
Ask again on invalid input without duplicating code.
Break / Continue
Same flow control as other loops.
Polling
Sample a value once, then repeatedly while needed.
Syntax
- Syntax: do { body } while (condition);
- A semicolon (;) is required after the closing
while(). - The body executes before the condition is checked.
- Useful when at least one iteration is needed.
Do-While Highlights
| Feature | Description | Example | Notes |
|---|---|---|---|
| Exit-controlled | Condition checked after body | do{...}while(c); | Always runs once |
| Semicolon | Mandatory after while() | while(x>0); | Common bug if missed |
| Best for | Menus / retries | Login retry | |
| Versus while | Pre-test vs post-test | while vs do-while |
Detailed Explanation & First Example
Let's start with a hands-on example. The program below shows the core idea behind Do While Loop in just a few lines of Java. Read it line by line and observe how Java executes each statement in order.
class Main
{
public static void main(String args[])
{
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
}
}
2
3
4
5
Examples — Beginner to Advanced
The following examples progress from simple to more practical patterns. Try each in your IDE, change the inputs and observe the output. This is the fastest way to internalize the concept.
class Main
{
public static void main(String args[])
{
int n = 10, sum = 0, i = 1;
do {
sum += i;
i++;
} while (i <= n);
System.out.println("Sum = " + sum);
}
}
import java.util.Scanner;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("1.Hello 2.Bye 3.Exit");
choice = sc.nextInt();
if (choice == 1) System.out.println("Hello!");
else if (choice == 2) System.out.println("Bye!");
} while (choice != 3);
}
}
class Main
{
public static void main(String args[])
{
int x = 100;
do {
System.out.println("Executed once");
} while (x < 10);
}
}
class Main
{
public static void main(String args[])
{
int n = 6789, rev = 0;
do {
rev = rev * 10 + n % 10;
n /= 10;
} while (n != 0);
System.out.println("Reverse = " + rev);
}
}
Notes & Tips
- Do not forget the semicolon after
while(condition). - Use do-while when you want the body to run at least once.
- Do-while is slightly less common than while, but very expressive for menus.
- Initialize variables before the loop, not inside the condition.
- Combine do-while with try-catch for input validation loops.
Real-World Use Cases
CLI Menus
Display options and repeat until the user chooses Exit.
Retry Login
Re-prompt for credentials after a failed login.
Sensor Sampling
Take an initial reading, then keep sampling while above a threshold.
Configuration Wizards
Step-by-step setup that always asks at least once.
Practice Questions
Reading is not enough — practice solidifies knowledge. Try every question below in your own editor before peeking at any solution.
- Q1. Write a do-while loop that prints all even numbers from 2 to 20.
- Q2. Build a menu program with 4 options using do-while.
- Q3. Sum digits of a number using do-while.
- Q4. Print factors of a number using do-while.
- Q5. Repeatedly ask the user for a positive number until they enter one.
Interview Questions
These are the most common questions asked in Java interviews on this topic. Memorize the concept, not just the answer — interviewers often follow up with edge cases.
while checks the condition before executing; do-while executes once then checks the condition, guaranteeing at least one run.
Whenever you want guaranteed first execution — menus, retries, and prompts.
Because the loop ends with an expression — the semicolon terminates the statement.
Yes —
do { … } while(true); creates an infinite loop.
No — performance is identical, only the order of check changes.
FAQ
Less than for/while, but ideal for menus and input validation.
Yes — nesting works the same way as any other loop.
Yes —
break exits a do-while just like any other loop.
Only if the body is a single statement, but braces are strongly recommended for clarity.
Some languages omit it. Java keeps it to handle clear at-least-once execution semantics.
Common Mistakes to Avoid
Even experienced developers slip on the same pitfalls. Watch out for these classic mistakes while working with Do While Loop in Java:
- Forgetting the semicolon
;at the end of statements while using Do While Loop. - Mixing up similar method names — read Java docs before using new APIs related to Do While Loop.
- Ignoring compiler warnings — they often hint at bugs that will appear later in production.
- Hard-coding values that should come from configuration files or environment variables.
- Not handling edge cases: empty inputs, very large inputs, negative numbers and null references.
- Skipping unit tests — small tests prevent big regressions, especially around control flow.
At-a-Glance
Best Practices
Follow Conventions
Use camelCase for variables, PascalCase for classes, UPPER_SNAKE for constants.
Write Tests
Cover happy path and edge cases with JUnit before shipping changes to production.
Keep Methods Short
A method should do one thing and fit on a single screen. Refactor when it grows.
Validate Inputs
Never trust user input. Validate at the boundary, fail fast and log meaningfully.
Comment the Why
Comments should explain why a decision was made — not what the code does line by line.
Refactor Often
Small frequent refactors are cheap and safe; big rewrites are risky and expensive.
Pro Tips
Quick Reference
| Keyword / Concept | Meaning | Used For | Java Since |
|---|---|---|---|
| Do While Loop | Do While Loop concept | Core Java | 1.0 |
| class | Blueprint of objects | OOP | 1.0 |
| static | Class-level member | Utilities | 1.0 |
| final | Constant / no override | Immutability | 1.0 |
| public | Accessible everywhere | API exposure | 1.0 |
| private | Class-only access | Encapsulation | 1.0 |
Related Topics
java.util, java.lang and java.io.
Summary
do-while is Java's exit-controlled loop — the body always runs at least once before the condition is checked. Use it for menus, retries, and any code that must execute initially regardless of state.