Do While Loop in Java Tutorial
Chapter 07 · Java Programming Series
PBA Institute 10 min read Beginner 2024

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

FeatureDescriptionExampleNotes
Exit-controlledCondition checked after bodydo{...}while(c);Always runs once
SemicolonMandatory after while()while(x>0);Common bug if missed
Best forMenus / retriesLogin retry
Versus whilePre-test vs post-testwhile 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.

Print 1 to 5 Using Do-While
class Main
{
    public static void main(String args[])
    {
        int i = 1;

        do {
            System.out.println(i);
            i++;
        } while (i <= 5);
    }
}
Output 1
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.

Sum of First N Natural Numbers
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);
    }
}
Output Sum = 55
Menu Program
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);
    }
}
Output Runs menu until user enters 3
Body Runs Even When Condition False
class Main
{
    public static void main(String args[])
    {
        int x = 100;

        do {
            System.out.println("Executed once");
        } while (x < 10);
    }
}
Output Executed once
Reverse Digits
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);
    }
}
Output Reverse = 9876

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.

Q1 What is the main difference between while and do-while?
while checks the condition before executing; do-while executes once then checks the condition, guaranteeing at least one run.
Q2 When should I prefer do-while?
Whenever you want guaranteed first execution — menus, retries, and prompts.
Q3 Why does do-while need a semicolon?
Because the loop ends with an expression — the semicolon terminates the statement.
Q4 Can a do-while loop be infinite?
Yes — do { … } while(true); creates an infinite loop.
Q5 Is do-while less efficient than while?
No — performance is identical, only the order of check changes.

FAQ

FAQ 1 Is the do-while loop used often?
Less than for/while, but ideal for menus and input validation.
FAQ 2 Can I nest do-while loops?
Yes — nesting works the same way as any other loop.
FAQ 3 Can break exit do-while?
Yes — break exits a do-while just like any other loop.
FAQ 4 Are braces optional for do-while?
Only if the body is a single statement, but braces are strongly recommended for clarity.
FAQ 5 Why is do-while uncommon in some languages?
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

Advantages
Readable Reusable Testable Standardized
Watch Out
Edge Cases Null Safety Performance Memory
Java Version
JDK 8+ JDK 11 JDK 17 LTS JDK 21 LTS
Pair With
While Loop String Functions OOP Best Practices

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

TIP 01 Use clear, descriptive identifiers when writing code involving Do While Loop — your future self will thank you.
TIP 02 Run small experiments in jshell (Java's REPL) to test ideas before committing them to a project.
TIP 03 Read the official java.lang and java.util documentation. The standard library is huge and surprisingly powerful.
TIP 04 Combine this topic with unit testing (JUnit 5) — it forces you to think about edge cases.
TIP 05 Practice with online judges (HackerRank, LeetCode) to internalise the patterns used in real interviews.

Quick Reference

Keyword / ConceptMeaningUsed ForJava Since
Do While LoopDo While Loop conceptCore Java1.0
classBlueprint of objectsOOP1.0
staticClass-level memberUtilities1.0
finalConstant / no overrideImmutability1.0
publicAccessible everywhereAPI exposure1.0
privateClass-only accessEncapsulation1.0

Related Topics

PREV While Loop — strengthens your understanding of the previous building block.
NEXT String Functions — the natural progression after mastering Do While Loop.
OOP Object Oriented Programming — Class, Object, Inheritance, Polymorphism, Encapsulation, Abstraction.
DSA Data Structures & Algorithms — apply this topic in real coding-interview challenges.
STD LIB Java Standard Library — explore 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.

Continue Learning