Do while loop in Java

(Last Updated On: February 25, 2019)

Learn do while loop in java programming with program examples and explanation. Also, code to run do while loop infinitely included. Know what difference between is while loop and do while loop.

Topics

  • Syntax of do -while loop with code example
  • Infinite do while loop
  • Difference between while and do while loop

A do while loop is like a while loop, except that do while loop executes its body at least once.

Syntax of do while loop in java:

 

Example of Do while loop in java

Printing number 1 to 10.

 

Infinite Do While loop

To run a do while loop infinitely, just we need to write true in while condition e.g. do{…}while(true).

Output:

Below string will be printed infinitely.

I am running infinitely…
I am running infinitely…
I am running infinitely…

 

Difference between while and do while loop

While loop in java may not run a single time when condition of Boolean expression is false. But in do while loop, it’s all statements in the body run at least once, as, control enters the loop first time in do{} and it checks the expression in while condition at the end.