Java do-while loop



Do-While Loop statement in Java : Exit Controlled Loop in Java

  1. In java “Do-while” is iteration statements like for loop and while loop.
  2. It is also called as “Loop Control Statement“.
  3. Do-while Statement”  is Exit Controlled Loop because condition is check at the last moment.
  4. Irrespective of the condition , control enters into the do-while loop , after completion of body execution , condition is checked whether true/false. If condition is false then it will jump out of the loop.
  5. Conditional Expression written inside while must return boolean value.
  6. In do-while loop body gets executed once whatever may be the condition but condition must be true if you need to execute body for second time.

do while loop flowchart

Syntax : Do-While Loop

do {
     Statement1;
     Statement2;
     Statement3;
     .
     .
     .
     .
     StatementN;
} while (expression);

*Note : Semicolon at the end of while is mandatory otherwise you will get compile error.

Live Example 1 : Printing Numbers

class DoWhile {
  public static void main(String args[]) {
    int n = 5;
    do
     {
     System.out.println("Sample : " + n);
     n--;
     }while(n > 0);
}

Output :

Sample : 5
Sample : 4
Sample : 3
Sample : 2
Sample : 1
Sample : 0