Java supports do while statement as other language support. do while statement in java is used to run program in loop on pre defined condition. do while statement can be implemented with while loop statement but expression condition is checked in last after running first cycle. This helps to run any java statement in block to execute on first cycle without checking conditions. We have to use do in top and while in last to make block. While statement must end with semi colon in last.
Java do while example explains how to use do while statement in java.
public class JavaDoWhileStatementExample { public static void main(String[] args) { int i=0; // Example first condition fail in first case do { System.out.println("do while loop iterator1 :"+i); i++; } while(i<0); int j=0; // Example second normal condition do { System.out.println("do while loop iterator2 :"+j); j++; } while(j<5); } }
Output
do while loop iterator1 :0
do while loop iterator2 :0
do while loop iterator2 :1
do while loop iterator2 :2
do while loop iterator2 :3
do while loop iterator2 :4
In above example, we are using do while with simple condition. In first example, condition fail in first case, but still it will go into do block and execute do while. This loop is supposed to execute 5 times. We are using condition to check loop, if it reach on 5 value of j. it will stop executing loop statement.
Tags: Java Statements



Link to Us