0
Explore
0

Do-While Loop in Java with examples

Updated on July 27, 2025

In Java, loops are used to repeat a block of code multiple times until a certain condition is met. Among the different types of loops, the do-while loop is special because it executes the code block at least once, even if the condition is false.

In this tutorial you will learn everything about the do-while loop from scratch. By the end, you’ll be able to write and understand do-while loops confidently.

What is a do-while loop?

A do-while loop is a type of loop that always runs the code at least once, because it checks the condition after running the loop body.

It is called a post-tested loop because the condition is tested after execution.

Key Point: Even if the condition is false, the loop will still run one time.

Syntax of do-while loop

do {
    // code to be executed
} while (condition);

Important Notes:

  • The semicolon (;) after the while(condition) is required.
  • The loop will keep executing as long as the condition is true.
  • Code inside the block runs before the condition is checked.

Flowchart of do-while loop

+------------------+
|  Execute block   |
+------------------+
         |
         v
+------------------+
|  Check condition |
+------------------+
         |
    +----+----+
    |         |
   Yes        No
    |          |
    v          x
 Repeat     Exit loop

Key Characteristics of do-while loop

FeatureDescription
Executes block at least onceYes
Condition checked at…After the block execution (post-test)
Ends with semicolonYes (while(condition);)
Useful for…Menu-driven programs, input validation, etc.

Example of do-while

Program to print numbers from 1 to 5

public class DoWhileExample {
    public static void main(String[] args) {
        int i = 1;
        do {
            System.out.println("Number: " + i);
            i++;
        } while (i <= 5);
    }
}

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Even if the condition was false initially, the first line would still execute.

Step-by-Step Explanation:

1. Variable Initialization:

int i = 1;

A variable i is declared and initialized with the value 1.

2. do Block:

do {
    System.out.println("Number: " + i);
    i++;
}
  • The code inside the do block runs first, without checking the condition.
  • It prints the value of i, then increases i by 1 (i++).

3. while Condition:

while (i <= 5);
  • After running the block once, it checks if i is less than or equal to 5.
  • If true, it repeats the loop.
  • If false, the loop stops.

🔢 Do-While Loop Execution:

i valueOutputCondition after incrementContinue?
1Number: 12 ≤ 5 → trueYes
2Number: 23 ≤ 5 → trueYes
3Number: 34 ≤ 5 → trueYes
4Number: 45 ≤ 5 → trueYes
5Number: 56 ≤ 5 → falseNo

Real-Life Example of do while

Think of brushing your teeth before checking your calendar.

You:

  1. Brush your teeth (task done once).
  2. Then check the calendar to see if it’s a working day (condition).
  3. If yes, repeat (e.g., get ready, pack bag, etc.).

Similarly, in a do-while, the task is always performed once before any condition check.

When to Use do-while vs. while

ScenarioUse whileUse do-while
You want to test condition first✅ Yes❌ No
You want the block to execute at least once❌ No✅ Yes
Suitable for menu/input-driven programs❌ Sometimes✅ Perfect fit

Nested do-while Loops

A nested do-while loop means placing one do-while loop inside another do-while loop. This structure is useful when you need to repeat a set of tasks multiple times within a bigger repeated process such as printing patterns or working with rows and columns.

The outer loop runs first and for each cycle of the outer loop, the inner loop runs completely. Even in a nested structure, each do-while loop ensures that its code block is executed at least once, regardless of the condition.

You can use one do-while loop inside another.

Example: Print 1 to 3, three times:

public class NestedDoWhile {
    public static void main(String[] args) {
        int i = 1;
        do {
            int j = 1;
            do {
                System.out.print(j + " ");
                j++;
            } while (j <= 3);
            System.out.println();
            i++;
        } while (i <= 3);
    }
}

Output:

1 2 3 
1 2 3 
1 2 3 

Using break and continue in do-while

In a do-while loop, you can use break to immediately exit the loop when a certain condition is met. On the other hand, continue skips the remaining code in the current iteration and moves directly to the next loop cycle, after checking the condition again. These keywords help you control the flow of the loop based on specific logic or conditions.

Break – exits loop immediately:

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

Output:

1 2 3

Continue – skips current iteration:

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

Output:

1 2 4 5

(Note: 3 is skipped)

Common Mistakes

MistakeCorrection
Forgetting ; after while(condition)Add semicolon like } while (condition);
Infinite loop due to no incrementMake sure to modify the loop variable
Misunderstanding: “It won’t run if condition is false”Wrong – It runs once even if false

Test Your Knowledge

Q1. What is the key difference between while and do-while?

Q2. How many times will the following code execute?

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

Q3. Fill in the blank to print numbers 1 to 5:

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

Practice Questions

  1. Write a Java program using do-while to calculate the sum of numbers from 1 to 100.
  2. Create a simple menu using do-while:
    • Press 1 for Addition
    • Press 2 for Subtraction
    • Press 3 to Exit
  3. Use do-while to reverse a number entered by the user.
  4. Create a program that keeps asking the user to enter a positive number, and stops only when a negative number is entered.

Conclusion

The do-while loop is a great concept when you want your code to run at least once before checking the condition. It’s especially useful in menu-driven applications, input validation, and games.

Challenge

Try writing a simple calculator that takes two numbers and a choice (1 for add, 2 for subtract, etc.) using a do-while loop. Exit when the user chooses 0.