Tutorials

Java Loop Control


Java do-while loop


The do-while loop in java is also used to execute a statement or the block of statement(s) just like while loop.
 
It should be used in case number of iteration is not known and when you want the code within do-while body to get executed at least once even when test condition evaluates to false.
 
Syntax:
 
do{
  //code to be executed
}while(testCondition);

 
Difference between while and do-while loop?
Example 1: We will go through two different examples to understand details about do-while loop. And both the example will help to differentiate between while and do-while loop.
 
public class printNumber {

    public static void main(String[] args) {
      int i = 1;
      do{
         System.out.println("value of i="+ i);
         i++;
       }while(i<10);
    }
}

OUTPUT:
value of i=1
value of i=2
value of i=3
value of i=4
value of i=5
value of i=6
value of i=7
value of i=8
value of i=9
 
Example 2:
 
public class printNumber {

    public static void main(String[] args) {
      int i = 10;   //assign a value so it fails test condition
      do{
         System.out.println("value of i="+ i);
         i++;
      }while(i<10);
   }
}

OUTPUT:
value of i=10
 


Please Share this page
Views : 43