Do-while loop in Java: execute the code block first, and then evaluate the condition


Keywords: do-while loop, conditional loop, loops

Do while loop Java programming

The final article in this chapter will look at the do-while loop in Java. A do-while loop is a conditional loop that is closely related to the while loop. We will see how we can use the do-while loop to first execute the loop’s code block, and then evaluate the condition. We will end the articles with a couple of examples that show the differences compared to the regular while loop and when the do-while loop may be favoured.

What is a do-while loop? 

The do-while loop is, as the name suggests, closely related to the while loop and therefore also a condition loop. This means repeating a code sequence, over and over again, until a condition is true. The difference between a do-while loop and a while loop is that the do-while loop performs the code block with all the operations first, and then evaluates the loop’s condition. In other words, the do-while loop performs all operations at least once.

In short, a do-while loop is:

  • A loop that repeats a sequence of operations as long as a condition is true.
  • Executes the operations in the code block first and then evaluates the condition.
  • Enables general and dynamic programs because you can reuse code.
  • Best suited when the number of iterations of the loop is not fixed.

The difference between do-while loop and while loop is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once

Oracle docs

How the do-while loop in Java works?

As mentioned, the do-while loop works similarly to the while loop that we saw on in the previous article. If we illustrate the do-while loop with a flow chart, we get figure 1 below.

Do-while loop Java

Figure 1: Do-while loop in Java

If we would describe what we see in Figure 1 with words

  • The do-while loop starts by executing the code block that contains a sequence of operations. 
  • When the code block is executed, the do-while loop proceeds to evaluate whether the condition is true or false.
  • If the condition is true, the loops goes back to the code block and performs the sequence of operations again. On the opposite, if the condition is false, the do-while loop is done and the program continues. 

How to create a do-while loop in Java

The do-while loop has many similarities with the while loop in functionality, but pay attention to the differences in the declaration.

  • The do-while loop is declared with the reserved word do, followed by curly brackets { }.
  • Within the curly brackets, you specify all the operations that you want to execute over and over again, as long as the condition is true. Remember, this code block will be performed at least once.
  • After the code block, you end the do-while loop by using the reserved word while followed by a condition in parentheses ( ). If this condition is true, the do-while loop will execute the code block again, continuously until the condition becomes false.
  • To end the loop we must use a semicolon ; after the parentheses 

Syntax: Declare do-while loop in Java

If we use the instructions in the list above:

do {

      // do-while loop code block

} while (condition);

Examples: Do-while loop in Java

Let’s look at a few examples of how to use a do-while loop in Java.

Example 1: Create a do-while loop in Java

Let’s start with a simple example to demonstrate how to use a do-while loop to print the value of a variable

public class Example{
   public static void main(String[] args) {

      int num = 0;                                       

      do{                                              
         System.out.println("num has the value: " + num);    
         num++;     

      } while (num < 3);   
   }
}                             

Furthermore, the result in this case will be:

num has the value: 0 
num has the value: 1 
num has the value: 2

However, if we change the value of the variable num to

int num = 20; 

and run our program again we would get the result

num has the value: 20

If we had used a while loop, the loop would never have started because the condition never becomes true, but since we use a do-while loop, the operation is always performed once before we evaluate if the condition of the loop is true.

If you would like to try the code in this example in an online compile, press the button below.

Example 2: Do-while loop using a random and scanner object

In this exercise we are going to: 

  • Ask the user to enter an integer between 0 – 9. We will use the built-in scanner class to save information from the user.
  • Generate a random integer between 0 – 9. We will use the built-in random class to generate a random number.
  • Print the number the user has entered, and then the generated random integer.
  • Use a do-while loop and continuously update the random number until the number specified by the user is the same as the random number.

By using a do-while loop, we will always get at least one result in the terminal, so in the case where the user’s specified number corresponds to the random number on the first try, we will also get a result.

 // Import the Random class
import java.util.Random;

// Import the Scanner class
import java.util.Scanner;

public class exempel {
        public static void main(String[] args) {

            // Creates a scanner object
            Scanner input = new Scanner(System.in);

            // Creates a random object
            Random rand = new Random();

            // Ask the user to enter information
            System.out.println("Enter an integer between 0-9");

            // Save the input from the user
            int num = input.nextInt();

            // Random integer between 0 - 9
            int randomNum = rand.nextInt(10);

            // Do-while loop
            do{

                // Generate a new random number
                randomNum = rand.nextInt(10);

                // Print information to the user
                System.out.println("User: " + num + 
                " : " + "Random number: " + randomNum);

            // As long input is different from random number
            } while (num != randomNum);
        }
}

Finally, in this case, it will be difficult to show the results because we get different answers every time. But a result might look like this:

User: 8 : Random number: 3
User: 8 : Random number: 6
User: 8 : Random number: 3
User: 8 : Random number: 0
User: 8 : Random number: 9
User: 8 : Random number: 8

Why use a do-while loop in Java?

Similar to the other loops, to avoid having to rewrite our code several times, we can instead repeat an operation several times with the do-while loop. The do-while loop repeats a code block as long as the condition of the loop is true. We usually use the do-while loop when we don’t know in advance how many times it will be repeated, but always want to perform at least one operation.

Summary: Do-while loop in Java

The do-while loop in Java is a conditional loop that is closely related to the while loop. Similarly to the while loop, a do-while loop repeats a code sequence as long the condition of the loop is true. The difference between a do-while loop and a while loop is that a do-while loop performs the code block with all operations first, and then checks the condition.

Syntax: Declare do-while loop in Java

do {

      // do-while loop code block

} while (condition);

FAQ: Do-while loop in Java

What’s the difference between a while loop and a do-while loop?

The difference between a do-while loop and a while loop is that a do-while loop performs the code block with all operations first, and then checks the condition. In other words, the do-wile loop performs the associated code block at least once.

How do I know if I should use the do-while loop or the while loop?

If you know for sure that you will perform the operations inside the code block at least once, then the do-while loop may be preferable. But the most common of the two, in our opinion, is the while loop.


Can I use multiple do-while loops inside each other?

Yes. Just keep in mind that loops can “get stuck” in an infinity loop so that you pay attention so that your program can move on from the loops.

How useful was this article?

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?