Do-While Loop in Java

Do-While Loop in Java

18 Apr 2024
Beginner
114 Views
11 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming For Beginners Free Course

do...while Loop in Java: An Overview

do...while loop in Java is the third type of looping statement in Java. In the Previous Java Tutorial, you have already learnt about the other two loops in Java, that are, for loop in Java and while loop in Java. In this tutorial, you will learn about What is do while loop in Java?, 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 that a block of code is 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.

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

Q1. What is do-while loop in Java?

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.

Q2. What is the difference between a while and a do-while 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.

Q3. What is called do-while loop?

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.

Q4. What is do-while loop syntax?

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

Q5. What are the two types of while loop?

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

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Self-paced Membership
  • 22+ Video Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Accept cookies & close this