Do While Loop in Java with Example

A do while loop in Java is a variant form of while loop. It is the same as a while loop, except that it executes the body of the loop 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 initially false, the body of loop will not execute at all and the control of execution will proceed to the next set of statements to execute.

However, sometimes, it might need to execute the body of a loop at least once before the test performs. We can handle such situations with the help of do while loop in Java.

The do while loop always executes its body at least once before the test evaluates because its test 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 for using do while loop in Java program is as:

Initialization;
do {
  // Loop body;
     Statement(s);
     Increment/decrement;
} while (test conditional expression);

In the above syntax, the keyword “do” is followed by a set of curly braces that encloses a block of code or statements. After “do” block, there is a “while” keyword followed by a conditional expression in parentheses.

This condition is a boolean expression that takes decision whether the loop should continue executing or not. If the condition evaluates to true, the loop will repeat to execute the code block. Otherwise, it will exit the loop.

Flowchart Diagram of Do While Loop Statement


The execution flowchart diagram for the do-while loop statement in Java has shown in the below figure.

Flowchart diagram of do while loop statement in Java

From the do-while loop flowchart, it is clear that the loop body executes first, and then the loop conditional expression evaluates to determine whether to continue or terminate the loop. If the evaluation is true, the loop body executes again. This process continues until the test condition is true.

When the specified condition is false, the loop ends. The control of execution comes out of the do-while loop and goes to the next statement that appears immediately after the while statement.

Since the specified condition testes at the bottom of the loop, the do…while loop provides an exit-controlled loop. The test condition must be boolean expression.

We do not need to use curly braces if there is only one statement inside the do…while loop.
[adinserter block=”5″]

How to Use Do While Loop in Java?


To use a Do-While loop in the Java programming, place the code block to be executed within the “do” section. After the code block, write the “while” keyword, followed by the conditional expression that must be satisfied for the loop to continue. You must properly intend the block of code within do while loop for better readability.

Consider the following example below.

 . . . . . 
 . . . . .
int i = 1, sum = 0;
do {
  sum = sum + i;
  i = i + 2;
}
while(sum < 40 || i < 10);
 . . . . . 
 . . . . . 

In this example, the body of loop will execute until one of the two relations is true.

Example Program based on do while loop


Let’s take a simple example program where we will display numbers from 1 to 6 in Java using do while statement.

Example 1:

package javaProgram;
public class Test {
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

a. In this example, the value of x is initially set to 1. Therefore, it is displayed 1.

b. Now, x++ statement will increment the value of x by 1, hence the value of x becomes 2. The conditional boolean expression x<=10 is tested.

c. 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.

d. Then the x value once again incremented and becomes 3. Since 3 is also less than 10, the flow once again goes back and displays x value.

e. In this way, this process continues until the value of x is less than or equal to 6.
[adinserter block=”2″]
f. 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 do while statement where we will display the multiplication table in Java.

Example 2:

package javaProgram;
public class Test {
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 consider an example in which we will use do while loop statement with user input.

Example 3:

package javaProgram;
import java.util.Scanner;
public class Test {
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

Example 4:

Let us write Java code to print the following pattern using nested do while loops.

*
* *
* * *
* * * *
* * * * *

package javaProgram;
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:
       * 
       * * 
       * * * 
       * * * * 
       * * * * * 

Difference between while loop and do-while loop


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.

⇐ Prev Next ⇒