Java do-while loop
Contents
Do-While Loop statement in Java : Exit Controlled Loop in Java
- In java “Do-while” is iteration statements like for loop and while loop.
- It is also called as “Loop Control Statement“.
- “Do-while Statement” is Exit Controlled Loop because condition is check at the last moment.
- 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.
- Conditional Expression written inside while must return boolean value.
- 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.
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