Home >Java >javaTutorial >What is the difference between while loop and do-while loop in Java?

What is the difference between while loop and do-while loop in Java?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBforward
2023-09-14 21:01:021449browse

What is the difference 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 beginning of each iteration. However, do-while loops test the loop continuation condition after the first iteration is complete. Therefore, a do-while loop guarantees that the loop logic is executed once, while a 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 be executed at all. However, one iteration of the do-while loop will be executed.

Output

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

The above is the detailed content of What is the difference between while loop and do-while loop in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete