Java Do While Loop

Do-While loop in java is similar to while loop except do-while loop evaluates its condition expression at the bottom of the loop instead of the top. Do While loop in java is used to execute a block of code multiple times.

Do while loop ensures that that code block inside do-while body will execute atleast once.

As the condition expression check is at the bottom of do-while loop block, it first execute it's code block and then decide whether to iterate again or not.

Syntax of do while Loop in Java
do {
    /* code to be executed */
    statement(s);
}while(condition);

Control flow of do while loop

First do-while loop execute the codes inside loop's body(statements inside {} braces). Then, the condition expression is tested. If the value of condition expression is true then code block of do while loop will be executed again otherwise the loop gets terminated.


Java Do While Loop Statement Control Flow Diagram
Points to Remember about do while Loop
  • Unlike for loop, there is no initialization and update statements.

  • The condition in do-while loop is a boolean expression.

  • We can also use infinite do while loops like while(1), which will never terminate. You should add terminating condition using break statement in order to terminate infinite while loop.
    For Example:
      do {
        if(....){
          break;
        }
      } while(1);

  • Opening and Closing braces are not required for single statement inside do while loop code block.
    For Example:
      do
          statement;
      while(condition);