do-while Loop
A do-while loop is similar to a while loop, but it checks the condition after running the block once. This guarantees the code inside runs at least one time, no matter what.
1. What is a do-while Loop?
A do-while loop is similar to a while loop, but it checks the condition after running the block once. This guarantees the code inside runs at least one time, no matter what.
2. Why is it used?
Some tasks must happen at least once before any check makes sense — like showing a menu to a user before asking if they want to continue. do-while guarantees this "at least once" behaviour.
3. Real-Life Example
Think of a food tasting session: "Taste the dish once, then decide if you want to taste it again." You always taste it at least once before deciding whether to repeat — that's exactly how do-while behaves.
4. Syntax
javado { // code runs at least once } while (condition);
5. Example Program
javapublic class DoWhileDemo { public static void main(String[] args) { int count = 1; do { System.out.println("Count: " + count); count++; } while (count <= 3); } }
Output:
Count: 1
Count: 2
Count: 36. Key Points to Remember
- The code block always runs at least once, even if the condition is false from the start.
- Note the semicolon after
while (condition);— a common beginner mistake is forgetting it. - Use
do-whilespecifically when "run at least once" behaviour is required.