What are the differences between while loop and do-while loop in Java?

The while loop in java executes one or more statements after testing the loop continuation condition at the start of each iteration. The do-while loop, however, tests the loop continuation condition after the first iteration has completed. Therefore, the do-while loop guarantees one execution of the loop logic whereas the while does not.


public class WhileAndDoWhileLoop {
   public static void main(String args[]) {
      int i=5;
      System.out.println("Test while Loop:");
      while(i < 5) {
         System.out.println("Iteration: "+ ++i);
      System.out.println("Test do-while Loop:");
      do {
         System.out.println("Iteration: "+ ++i);
      } while(i < 5);

In the above example, The while loop statement will not execute at all. However, one iteration of the do-while loop will execute.


Test while Loop:
Test do-while Loop:
Iteration: 6