What is the do while loop in Java?

The do…while loop is nearly identical to the while loop, but instead of checking the conditional statement before the loop starts, the do…while loop checks the conditional statement after the first run, then continues onto another iteration.

Syntax:

do{
// body
} while(condition);

As you can see, this will run the loop at least once before checking the conditional.

Following is an example of do…while loop in Java:

class HelloWorld{
public static void main(String[] args){
int number=5;
do{
System.out.println("Value of number is: "+ number);
number++;
} while(number<=9); // the condition is being checked after the first run
}
}

Why use do-while?

A do-while loop is used where your loop should execute at least one time. For example, let’s say you want to take an integer input from the user until the user has entered a positive number. In this case, we will use a do-while as we have to run the loop at-least once. The loop takes an initial input, and it will continue running until the user enters a positive number.

svg viewer
Copyright ©2024 Educative, Inc. All rights reserved