How to Use Do While Loop in Java: Syntax and Examples
In Java, a
do while loop executes the code block once before checking the condition at the end of the loop. It repeats the block as long as the condition is true, ensuring the code runs at least one time.Syntax
The do while loop syntax in Java consists of the do keyword followed by a block of code inside curly braces, and then the while keyword with a condition in parentheses. The loop runs the code block first, then checks the condition to decide if it should repeat.
- do: starts the loop block
- code block: statements to run at least once
- while(condition): checks if the loop should continue
- semicolon: ends the
do whilestatement
java
do { // code to execute } while (condition);
Example
This example shows a do while loop that prints numbers from 1 to 5. It runs the print statement first, then checks if the number is less than or equal to 5 to continue.
java
public class DoWhileExample { public static void main(String[] args) { int count = 1; do { System.out.println("Count is: " + count); count++; } while (count <= 5); } }
Output
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Common Pitfalls
One common mistake is forgetting the semicolon ; after the while(condition) line, which causes a syntax error. Another is using a condition that never becomes false, leading to an infinite loop. Also, confusing do while with while loops can cause logic errors because do while always runs at least once.
java
/* Wrong: Missing semicolon causes error */ do { System.out.println("Hello"); } while (false) // <-- missing semicolon here /* Correct: Semicolon included */ do { System.out.println("Hello"); } while (false);
Quick Reference
- Use do while when you want the code to run at least once.
- Check condition after the code block.
- End with semicolon after the while condition.
- Avoid infinite loops by ensuring the condition will become false.
Key Takeaways
The do while loop runs the code block first, then checks the condition to repeat.
Always end the do while statement with a semicolon after the while condition.
Use do while when you need the loop to execute at least once regardless of the condition.
Avoid infinite loops by making sure the loop condition eventually becomes false.
Common errors include missing semicolon and confusing do while with while loops.