Home > Java > javaTutorial > body text

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

WBOY
Release: 2023-09-14 21:01:02
forward
1307 people have browsed it

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);
   }
}
Copy after login

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
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!