- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements