Difference between a while and a do-while loop in java.

Modified on Tue, 28 Mar, 2023 at 3:53 PM

While loop checks the condition first and then executes the statement(s), whereas do while loop will execute the statement(s) at least once, then the condition is checked.

While loop is entry controlled loop, whereas do while is exit controlled loop.

In the while loop, we do not need to add a semicolon at the end of a while condition, but we need to add a semicolon at the end of the while condition in the do-while loop.

While loop statement(s) is executed zero times if the condition is false, whereas the do-while statement is executed at least once.

While loop allows initialization of counter variable before starting the body of a loop, whereas do while loop allows initialization of counter variable before and after starting the body of a loop.

Look at the example given below:

The while loop does not execute because the condition in false i.e., i is not greater than 0.

The same condition is applied to the do-while loop, but it gives the output at least once as the condition is checked at the last after executing the statements.

So, when you want to execute some statements at least once, whether the condition is true or false, then use do-while loop.

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article