Trusted answers to developer questions

What is the do while loop in Java?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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

RELATED TAGS

do-while
do while
java
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?