Do While Loop
Do While Loop
A school program needs reliable data and clear rules. A do-while loop runs its body before checking whether to repeat. This is useful for an action that must happen at least once.
Understand
A do-while loop runs its body before checking whether to repeat.
Apply
Trace the Java example, predict its output and explain the result before running it.
Avoid mistakes
Even a false initial continuation condition cannot prevent the first body execution. The trailing semicolon belongs to this syntax.
Do While Loop
In Java, unlike the while loop, which checks the condition before executing the code block, the do-while loop guarantees at least one execution—no matter what the condition says. It's a perfect fit when your logic requires the body to run before validation kicks in.
What is a Do-While Loop?
A do-while loop in Java is a control flow statement that executes a block of code at least once, and then continues to execute it as long as the specified condition is true.
Syntax of Do-While Loop
do {
// Code to execute
} while (condition);
Note: The semicolon after the while condition is required. This often trips up beginners, so keep an eye on it!
Step-by-Step Example
public class Main {
public static void main(String[] args) {
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count <= 3);
}
}
Count is: 1
Count is: 2
Count is: 3
How It Works
Here’s what happens line-by-line:
countstarts at 1.- The
doblock runs and prints “Count is: 1”. countincrements to 2, and the loop condition(count <= 3)is checked.- Since it's still true, the block runs again. This continues until
countbecomes 4. - At
count = 4, the condition fails, and the loop exits.
Why Use a Do-While Loop?
The do-while loop shines in scenarios where the loop body must execute at least once before the condition is checked. For example:
import java.util.Scanner;
public class LoginPrompt {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String password;
do {
System.out.print("Enter your password: ");
password = scanner.nextLine();
} while (!password.equals("admin123"));
System.out.println("Access granted.");
}
}
Enter your password: user1
Enter your password: hello
Enter your password: admin123
Access granted.
This loop ensures that the user is always prompted at least once. The moment the correct password is entered, it breaks out of the loop.
Edge Case: False Condition from Start
public class Main {
public static void main(String[] args) {
int x = 100;
do {
System.out.println("This will run once even if condition is false.");
} while (x < 50);
}
}
This will run once even if condition is false.
Unlike while or for loops, a do-while will not skip execution—even if the condition is false from the beginning.
Best Practices
- Use
do-whilewhen the logic demands at least one execution. - Make sure the loop condition eventually becomes false to avoid infinite loops.
- Use meaningful loop conditions—especially in user input scenarios.
Do-While vs While: Quick Comparison
| Aspect | do-while | while |
|---|---|---|
| Condition check | After execution | Before execution |
| Minimum executions | 1 | 0 |
| Use case | User prompt, menus | Loops with known condition upfront |
Conclusion
The Java do-while loop is more than just a variation of while; it’s a purposeful construct tailored for specific use cases. When you're certain that your block of code needs to run at least once, do-while loop is the one you have to use.
Important boundaries and mistakes
Even a false initial continuation condition cannot prevent the first body execution. The trailing semicolon belongs to this syntax.
Try the school example
Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: Even a false initial continuation condition cannot prevent the first body execution.
Java 17 · Main.java · complete practice program
public class Main {
public static void main(String[] args) {
int attempts = 0;
do {
attempts++;
}
while (attempts < 0);
System.out.println(attempts);
}
}
Now change one thing: Start attempts at 5. Predict the new behavior before checking the worked variation.
Worked answer and reasoning
Java 17 · Main.java · source repeated for this answer
public class Main {
public static void main(String[] args) {
int attempts = 0;
do {
attempts++;
}
while (attempts < 0);
System.out.println(attempts);
}
}
Expected output
1A do-while loop runs its body before checking whether to repeat. This is useful for an action that must happen at least once.
Even a false initial continuation condition cannot prevent the first body execution. The trailing semicolon belongs to this syntax.
Run with javac Main.java, then java Main. The declaration of Main names the class; main starts the example, and println writes a complete output line.
Worked variation: Start attempts at 5. The body still runs once and prints 6.
Check your understanding
Check a common mistake
What to remember
A do-while loop runs its body before checking whether to repeat. This is useful for an action that must happen at least once. Even a false initial continuation condition cannot prevent the first body execution. The trailing semicolon belongs to this syntax.
Related explanations: Java Variables, Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects, Exceptions in Java Introduction.
Supporting documentation: Official Java learning guide and Java 17 language specification.
Reaching the recap and completing the quizzes are separate milestones.