Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

do-while
do while
java

What is the do while loop in Java?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring