A do while loop in Java is a variant form of the while loop. It is similar to the while loop, except that the do-while loop executes the loop body first and then evaluates the loop continuation condition.
In the while loop statement, the test condition evaluates first before the loop body executes. If the condition is false initially, the loop body will not execute even once, and control moves to the next statement.
However, in some situations, it might need to execute the loop body at least once, regardless of whether the condition is true or false. In such cases, we use a do-while loop in Java.
The do-while loop always executes its body at least once before the test evaluates because its conditional expression is at the bottom of the loop. It is especially useful when we want to execute a certain block of code at least once, regardless of whether the loop condition is initially true or false.
Syntax of Do While Loop in Java
The general syntax of do-while loop in Java is:
Initialization;
do {
// Loop body;
Statement(s);
Increment/decrement;
} while (test_condition);
In the above syntax:
- The keyword do is followed by a block of code enclosed in curly braces {}.
- After the do block, there is a while keyword followed by a conditional expression inside parentheses ().
- Important: The while statement ends with a semicolon (;), which is mandatory in a do-while loop.
The condition is a boolean expression that decides whether the loop should continue executing:
- If the condition evaluates to true, the loop repeats and executes the code block again.
- If the condition evaluates to false, the loop terminates, and control moves to the next statement after the loop.
Flowchart Diagram of Do While Loop Statement
The execution flowchart diagram for the do-while loop statement in Java is shown below.
Working of Do-While Loop in Java
From the do-while loop flowchart, it is clear that the loop body executes first, and then the conditional expression is evaluated to determine whether the loop should continue or terminate.
If the condition evaluates to true, the loop body executes again. This process continues as long as the condition remains true. When the condition becomes false, the loop terminates.
After the loop ends, the control of execution moves to the next statement immediately after the do-while loop. Since the condition is tested at the bottom of the loop, the do-while loop is known as an exit-controlled loop. The test condition must be a boolean expression (i.e., it should return true or false).
If there is only one statement inside the loop, using curly braces {} is optional, but it is considered a good practice to use them for better readability and to avoid errors.
How to Use Do-While Loop in Java?
To use a do-while loop in Java, place the code block to be executed inside the do block. After the block, write the while keyword followed by a conditional expression that determines whether the loop should continue. You must properly indent the block of code within do while loop for better readability.
Consider an example below.
int i = 1, sum = 0;
do {
sum = sum + i;
i = i + 2;
}
while (sum < 40 || i < 10);
In this example:
- The loop continues as long as the condition is true.
- The condition used is sum < 40 || i < 10.
- This means the loop will continue if at least one of the two conditions is true:
- sum < 40 OR
- i < 10
- The loop will stop only when both conditions become false.
Java Do While Loop Example Program
Let’s take a simple example program where we will display numbers from 1 to 6 in Java using do while statement.
Example 1: Print Numbers from 1 to 6
public class Numbers {
public static void main(String[] args)
{
// Initialize the counter.
int x;
x = 1; // starting number is 1.
// Execute the loop at least once and print the value of x.
do {
System.out.println(x); // print x value.
x++; // increment x value by 1.
} while(x <= 6); // This statement will execute as long as x <= 6.
}
}Output:
1 2 3 4 5 6
In this example:
- The value of x is initially set to 1. Therefore, it is displayed 1.
- Now, x++ statement will increment the value of x by 1. Hence, the value of x becomes 2.
- The conditional boolean expression x <= 6 is tested.
- Since this condition is true, the flow of execution will go back and the value of x, i.e. 2 will be displayed on the console.
- Then, the value of x once again incremented and becomes 3. Since the value 3 is also less than 10, the flow once again goes back and prints x value.
- In this way, this process continues until the value of x is less than or equal to 6.
- As the value of x is greater than 6, the condition will be false and the loop will be terminated.
Let’s another example program based on the nested do-while statement where we will display the multiplication table in Java.
Example 2: Multiplication Table
public class MultiplicationTable {
public static void main(String[] args)
{
int row, column;
System.out.println("Multiplication Table \n");
row = 1; // Initialization.
do {
column = 1;
do{
int x = row * column;
System.out.printf("%4d", + x);
column = column + 1;
} while(column <= 5);
System.out.println("\n");
row = row + 1;
} while(row <= 5);
}
}Output:
Multiplication Table: 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25
In this example program, the do-while loop is in nested form and produced the following output.
Let us take an example in which we will calculate the sum of numbers entered by the user using a do-while loop statement until the user enters 0.
Example 3: Calculate Sum of Numbers
import java.util.Scanner;
public class AdditionEx {
public static void main(String[] args)
{
int num = 0, sum = 0;
// Create an object of Scanner class to take input.
Scanner sc = new Scanner(System.in);
// Continue reading data until the input is 0.
do {
// Read the next input.
System.out.println("Enter an integer number: ");
num = sc.nextInt();
sum = sum + num;
} while(num != 0);
System.out.println("Sum of numbers: " +sum);
}
}Output:
Enter an integer number: 20 Enter an integer number: 10 Enter an integer number: 5 Enter an integer number: 40 Enter an integer number: 0 Sum of numbers: 75
This Java program demonstrates how to use a do-while loop to repeatedly accept integer input from the user and calculate their sum.
- The program uses the Scanner class to take input from the user.
- It continuously prompts the user to enter integer numbers.
- Each entered number is added to the variable sum.
- The loop continues executing until the user enters 0.
- When 0 is entered, the loop terminates, and the program displays the total sum of all entered numbers (including 0, which does not affect the sum).
Example 4: Star Pattern
Let us write Java code to print the following pattern using nested do-while loops in Java.
*
* *
* * *
* * * *
* * * * *
public class StarPatternEx {
public static void main(String[] args)
{
// Nested Do-While loop to print a pattern
int i = 1;
// Outer do while statement.
do {
int j = 1;
// Inner do while statement.
do {
System.out.print("* ");
j++;
} while (j <= i); // Inner do while loop ends here.
System.out.println();
i++;
} while (i <= 5); // Outer do while loop ends here.
}
}
Output:
* * * * * * * * * * * * * * *
When Should You Use Do-While Loop?
You should use a do-while loop when you want the code to run at least once, and the condition needs to be checked after execution.
Difference between While Loop and Do-While Loop in Java
The difference between while loop and do-while loop statements in Java is as follows:
1. Test condition verified:
- In the case of while loop, the first test condition is verified and then executes the statements inside the while block.
- While, in the case of do-while loop, the first statements inside do block are executed and then the test condition is verified.
2. Execution of block statements:
- If the test condition is false for the first time, then the block of statement executed zero times.
- If the test condition is false for the first time, then the block of statement executed at least once time.
3. Syntax:
- In the while syntax, while statement is at the top.
- In the do-while syntax, while statement is at the bottom.





