Java do-while Loop

Introduction

The Java do-while loop is one of the three primary looping statements in Java, alongside the for loop and the while loop. It is used to execute a block of code repeatedly as long as a specified condition is true. However, unlike the while loop, the do-while loop guarantees that the loop body executes at least once, even if the condition is false initially.

This unique behavior makes the do-while loop ideal for situations where an operation must be performed before checking whether it should repeat.

For example:

  • Display a menu at least once before asking the user to continue.
  • Repeat a game until the player chooses to quit.

What is Java do-while Loop?

The Java do-while loop is an exit-controlled loop that executes a block of code first and then checks the loop condition.

If the condition is true, the loop repeats. If the condition is false, the loop terminates.

The key feature of a do-while loop is that the loop body always executes at least one time, regardless of the condition.

How It Works

The execution process is:

  1. Execute the statements inside the do block.
  2. Evaluate the condition after execution.
  3. If the condition is true, repeat the loop.
  4. If the condition is false, exit the loop.

Syntax


do {
    // Code to execute
} while (condition);

Explanation

  • do starts the loop.
  • The statements inside the block execute first.
  • while checks the condition after execution.
  • The semicolon (;) after the while condition is mandatory.

Flow of Java do-while Loop

The execution flow is:


        Start
          |
 Execute Loop Body
          |
   Check Condition
     /          \
  True         False
    |             |
    |         End Loop
    |
 Execute Again

Unlike the while loop, the condition is checked after executing the loop body.

Example 1: Print Numbers from 1 to 5


public 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

Explanation

  • The loop starts by printing 1.
  • After each iteration, i is incremented.
  • The loop continues until i becomes 6.

Example 2: Print Even Numbers


int number = 2;
do [
    System.out.println(number);
    number += 2;
} while (number <= 10);

Output

2
4
6
8
10

Example 3: Calculate the Sum of Numbers


int i = 1;
int sum = 0;
do {
    sum += i;
    i++;
} while (i <= 5);
System.out.println("Sum = " + sum);

Output

Sum = 15

Example 4: Countdown Timer


int count = 5;
do {
    System.out.println(count);
    count--;
} while (count > 0);

Output

5
4
3
2
1

Example 5: Condition is False Initially


int number = 10;
do {
    System.out.println("Executed Once");
} while (number < 5);

Output

Executed Once

Although the condition is false, the loop executes once because the condition is checked afterward.

Real-life Examples

1. ATM Menu


int option = 1;
do 
    System.out.println("ATM Menu");
    option++;
} while (option <= 3);

The menu is displayed at least once before checking whether the user wants to continue.

2. Login Attempts


int attempts = 1;
do {
    System.out.println("Login Attempt: " + attempts);
    attempts++;
} while (attempts <= 3);

3. User Input Validation


int value = 0;
do {
    System.out.println("Enter a Positive Number");
    value++;
} while (value <= 0);

4. Play Again Option


char choice = 'Y';
do {
    System.out.println("Playing Game");
    choice = 'N';
} while (choice == 'Y');

5. Shopping Cart


int item = 1;
do {
    System.out.println("Processing Item " + item);
    item++;
} while (item <= 5);

Infinite do-while Loop

A do-while loop becomes infinite when the condition always evaluates to true.


do {
    System.out.println("Running...");
} while (true);

Common Uses

  • Game loops
  • Chat applications
  • Server processes
  • Background services
  • Event listeners

Always provide a way to terminate the loop if necessary.

Java do-while Loop vs while Loop

Feature do-while Loop while Loop
Condition Check After execution Before execution
Minimum Executions One Zero
Loop Type Exit-controlled Entry-controlled
Best For Menus, user input, validation Unknown iterations

Java do-while Loop vs for Loop

Feature do-while Loop for Loop
Best For At least one execution required Known number of iterations
Condition Check After execution Before execution
Initialization Before loop Inside loop
Update Inside loop body In loop declaration

Advantages of Java do-while Loop

  • Executes the loop body at least once.
  • Ideal for menu-driven programs.
  • Useful for user input validation.
  • Simple and easy to understand.
  • Reduces repetitive code.
  • Frequently used in interactive applications.
  • Suitable for scenarios where an initial action is mandatory.

Common Mistakes

1. Forgetting the Semicolon

Incorrect:


do {
    System.out.println("Hello");
} while (true)

Correct:


do {
    System.out.println("Hello");
} while (true);

The semicolon after the while condition is required.

2. Forgetting to Update the Loop Variable

Incorrect:


int i = 1;
do {
    System.out.println(i);
} while (i <= 5);

This creates an infinite loop because i never changes.

Correct:


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

3. Wrong Loop Condition

Incorrect:


int i = 5;
do {
    System.out.println(i);
    i++;
} while (i < 5);

The loop executes only once because the condition becomes false immediately.

4. Creating Unnecessary Infinite Loops

Avoid using:


do {
} while (true);

unless your application intentionally requires continuous execution.

5. Missing Braces

Although Java allows single statements without braces, always use braces to improve readability and reduce errors.

Best Practices

📖
Best Practices:
  • Use the do-while loop only when at least one execution is required.
  • Keep loop conditions simple and easy to understand.
  • Always update the loop variable to avoid infinite loops.
  • Use meaningful variable names.
  • Keep the loop body concise.
  • Add comments for complex logic.
  • Use braces even for a single statement

When Should You Use a do-while Loop?

Use a do-while loop when:

  • A menu should appear at least once.
  • User input must be requested before validation.
  • The loop body should execute regardless of the initial condition.
  • Building interactive console applications.
  • Creating games or repeated user interactions.

Conclusion

The Java do-while loop is an important looping construct that guarantees the execution of a block of code at least once. Unlike the while loop, which checks the condition before execution, the do-while loop checks the condition afterward, making it an excellent choice for menu-driven programs, user input validation, and interactive applications.

Java Do While loop – Interview Questions

Q 1: What is do-while loop?
Ans: A loop that executes at least once.
Q 2: Is do-while entry or exit-controlled?
Ans: Exit-controlled loop.
Q 3: When is condition checked in do-while?
Ans: After executing loop body.
Q 4: Can do-while run without condition?
Ans: No, condition is mandatory.
Q 5: Where is do-while commonly used?
Ans: Menu-driven programs.

Java Do While Loop – Objective Questions (MCQs)

Q1. Which of the following is the correct syntax for a do-while loop in Java?






Q2. What is the key difference between a while loop and a do-while loop?






Q3. What will be the output of the following code?

int int i = 1;
do {
System.out.print(i + ' ');
i++;
} while (i <= 3);






Q4. What will be the output of the following code?

int x = 10;
do {
System.out.println("Hello");
} while (x < 5);






Q5. How many times will this loop execute?

int n = 5;
do {
n++;
} while (n < 5);






Related Java Tutorials