«Back to Home

Core Java

Topics

Do While Loop In Java

do-while loop

There is another loop control structure which is very similar to the while statement called as do while statement. The only difference is that the expression which determines whether to carry on looping is evaluated at the end of each loop.
 
Syntax

do {
Statements;
} while (test condition);
 
Let’s understand with the flowchart, given below.

60
 
In do-while loop, the loop body is executed at least once, if condition is false. The loop repeats body , when the condition is true. However, in while loop, the statement doesn’t execute the body of the loop even once, if the condition is false. Due to this “do-while loop” is also called exit-control loop.
 
Let’s see an example of do-while loop, given below.
 
Code
  1. public class DoWhileExm {  
  2.     public static void main(String[] args) {  
  3.         int n = 1;  
  4.         do {  
  5.             System.out.println("do-while loop : " + n);  
  6.             n++;  
  7.         } while (n < 10);  
  8.     }  
  9. }  
69

Output

70
 
Summary

Thus, we learnt “do while loop” is very similar to the while statement. The only difference is that of the expression and also learnt how to create it in Java.