do...while Loop in Java - Flowchart & Syntax (With Examples)

do...while Loop in Java - Flowchart & Syntax (With Examples)

09 Sep 2024
Beginner
3.95K Views
12 min read
Learn with an interactive course and practical hands-on labs

Java Online Course Free with Certificate

do...while Loop in Java

do...while loop in Java is the third type of looping statement in Java. It prints the output at least once before checking the condition. Afterwards, the condition is checked and the execution of the loop begins.

In the previous Java Tutorial, you have already learned about the other two loops in Java, for loop in Java and while loop in Java. In this tutorial, you will learn to do...while loop in Java syntax, do...while loop in Java example, and much more. To explore more about different concepts of Java Programming, enroll in our Java Certification Training right now!!

Read More: Top 50 Java Interview Questions and Answers

What is do...while Loop in Java?

The do...while loop in Java is also known as Exit Control Loop. It is used by Java Developers when they want a block of code to be executed at least once before checking the condition. After the execution, the specified condition is evaluated to decide whether the loop will be repeated or not.

Flowchart of do...while loop in Java

Java do...while loop flowchart

Syntax of do...while loop in Java

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

Explanation:

  • The 'do' block has a block of code that is executed first.
  • Then, the loop checks the condition that is specified inside the 'while' statement.
  • If that condition evaluates to be 'True', the loop body will execute again. It repeats execution until the condition is true.
  • Once the condition becomes 'False', the loop will terminate and the program will carry on to the next statement that is just after the do...while loop.

How do...while loop works?

Lets understand how execution of do...while loop occurs in Java step by step:
  1. Initialization The loop starts and the code that is in the 'do' block is executed first.
  2. Execution The program executes all every statement that is present in the 'do' block in sequence.
  3. Condition Check When the execution of the loop body is done once, the condition specified in the 'while' statement is checked.
  4. Conditional Execution If the condition evaluates to be 'True', the execution of the loop body is repeated. The process repeats from step 2. But if the condition evaluates to be 'False', the loop will immediately terminate and the program will carry on with the next statement just after the do...while loop.
  5. Loop Termination In this way, the loop will continue repeating execution of the loop body until the condition is true. Once it becomes false, the loop will terminate.

ScholarHat’s Java Full-Stack certification puts you on the fast track to success.

Training NamePrice
Full-Stack Java Developer Training (Start Earning ₹3 - ₹9 LPA* in Software Jobs)Book a FREE Live Demo!

Read More: Java Developer Salary Guide in India – For Freshers & Experienced

do...while loop in java with example

Lets have a look at some of the Java do while loop example programs in a Java Compiler to understand them better:

1. Sum of Numbers

public class DoWhileExample1 {
    public static void main(String[] args) {
        int i = 1;
        int sum = 0;
        
        do {
            sum += i;
            i++;
        } while (i <= 5);
        
        System.out.println("Sum of numbers from 1 to 5 is: " + sum);
    }
}
The above program will result in the sum of all the numbers from 1 to 5 as shown in the below output.

Output

Sum of numbers from 1 to 5 is: 15

2. Guessing Game

import java.util.Scanner;

public class DoWhileExample2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int secretNumber = 3;
        int guess;
        
        do {
            System.out.print("Guess the number between 1 and 5: ");
            guess = scanner.nextInt();
            
            if (guess != secretNumber) {
                System.out.println("Wrong guess. Try again!");
            }
        } while (guess != secretNumber);
        
        System.out.println("Congratulations! You guessed the correct number.");
        scanner.close();
    }
}
In this example, the do...while loop prompts the user for guessing a secret number. If the user guesses an incorrect answer, the loop will continue to prompt the user till they guess the right one. Once the user has guessed the right number which is '3' here, the loop will terminate immediately displaying a congratulatory message.

Output

Guess the number between 1 and 5: 2
Wrong guess. Try again!
Guess the number between 1 and 5: 4
Wrong guess. Try again!
Guess the number between 1 and 5: 3
Congratulations! You guessed the correct number.

Components of do...while Loop

In Java, the do...while loop consists of two main components that are as follows:

1. Test Expression

The test expression is the part of the do...while loop that has a condition in it. The condition is checked after every execution to determine whether the loop body will be executed again or not. If the condition evaluates to be 'True', the loop repeats the execution of the loop body. If it evaluates to be 'False', the loop terminates immediately.

2. Update Expression

The update expression in the do...while is the one that updates the variable of the loop. It may increment or decrement depending on the specifications. The update expression makes sure that at some point the test expression will evaluate to 'False' and the loop will terminate eventually.

Example:

Consider this example below in Java Online Editor to identify both the expressions of the do...while loop.
int i = 1;
do {
    System.out.println(i);
    i++;
} while (i <= 5);
In this example,
  • 'i <= 5' is the Test Expression
  • 'i++' is the Update Expression

Use Cases of do...while Loop

There are many cases where we can use do...while loop in our Java Programs. Some of them are listed below:

1. Menu-Driven Programs

do...while loops are very commonly used in menu-driven programs. A menu of options is presented to the user in such cases to which they need to make a selection. The loop executes to display the menu at least once and then, waits for the user to choose an option from the menu.

2. Input Validation

This loop is very useful when it comes to validating user input. With the help of do...while loop, the user is prompted for the input until they enter a valid input. It makes sure that certain important field is not left empty and a value is inserted to it.

3. Game Loops

The do...while loops also work well in game development. They can be used under conditions where the game logic is executed once and it is repeated until certain condition is met which can be like game over or when the player exits the game.

4. Sequential Processing

It can also be used when you are processing elements in an array or collection sequentially. A do...while will execute the loop body at least once for each element.

5. Timed Loops

The timed loops are those where a block of code needs to be executed for a fixed duration of time. In such conditions, a do...while loop can be used with time tracking mechanisms like 'System.currentTimeMillis()' that will keep a track of time and the loop will continue until the desired duration of time.

Advantages of do...while loop in Java

  • a do...while loop makes sure that the loop body is executed at least once before checking the condition.
  • Any necessary initialization can be done easily as it the loop condition is checked after executing it once.
  • The code is more readable and intuitive.
  • It is very useful in cases where input validation is required.
  •  Repetitive codes can be encapsulated inside the loop body when using a do...while loop making the code reusable and reducing redundancy.

Disadvantages of do...while loop in Java

  • Using do...while loops can be quite complex sometimes especially when they are used with multiple conditions or nested loops.
  • There are chances of do...while loops resulting in to infinite loops where the loop execution continues indefinitely. This can happen if the loop condition is not properly defined or if it is not updated within the loop body.
  • There is less control over the starting of the loop as the loop body is executed once for sure before checking the loop condition.
  • It has limited use cases as compared to the other two loops in Java, that are, for loop and while loop.

Summary

Through this article, we learnt about do...while loop in Java in deep and also its basic structure and usage through related examples. If you are a newbie to Java Programming, we recommend you to enroll in our Java Programming Course to get a better understanding with a step by step comprehensive guide to Java.

FAQs

A do-while loop in Java is used for executing a block of code at least once before it checks the condition specified in the loop.

The main difference between both the loops is that a while loop checks the condition at the beginning and may not execute the loop body at all. Whereas, a do-while loop executes the loop body first and then checks the condition so it is executed at least once.

A do-while loop is also called an Exit Control Loop that executes the loop body at least once and then, repeats the execution on the basis of evaluation of the condition inside the loop.

Here is the syntax of do-while loop:
do {
    // Code block to execute
} while (condition);

The two types of while loop in Java are:
  1. while loop
  2. do-while loop
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this