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.

Example

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:");
      i=5;
      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.

Output

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

Updated on: 21-Nov-2023

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements