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.
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.
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!