Lesson Completion
Back to course

do-while Loop: Execute First, Check Later

Beginner
15 minutesβ˜…4.6Java

1. The Hook (The "Byte-Sized" Intro)

In a Nutshell: The do-while loop executes the body first, then checks the condition. It guarantees at least one execution, unlike while.

When ATMs show the menu: do { displayMenu(); } while (choice != exit). Menu always shows once, even if you exit immediately!


2. Conceptual Clarity (The "Simple" Tier)

πŸ’‘ The Analogy: Try Before You Buy

Think of do-while as a free sample station:

  • do block = Get a free sample (happens first)
  • while condition = "Want another?" (checked after)

You always get the first sample, then decide if you want more!

Visual Map

graph TB Start["Start loop"] --> Execute["Execute body FIRST<br/>(always runs once)"] Execute --> Check{while condition?} Check -- true --> Execute Check -- false --> Exit["Exit loop"] style Execute fill:#2E7D32 style Check fill:#F57C00

3. Technical Mastery (The "Deep Dive")

πŸ“˜ Formal Definition

Syntax:

java
do { // Loop body // Executes at least once } while (condition); // ⚠️ Semicolon required!
  • Exit-controlled: Condition checked after each iteration
  • Guaranteed execution: Body always runs at least once
  • Semicolon: Required after while(condition);

The "Why" Paragraph

do-while is perfect for menu-driven programs, input validation, and "try-then-check" scenarios. When you need to act first, then decide if you should repeat, do-while makes intent clear. It's less common than while but crucial when that first execution is mandatory.


4. Interactive & Applied Code

Complete Example

java
public class DoWhileDemo { public static void main(String[] args) { // Basic do-while int count = 1; do { System.out.println("Count: " + count); // Executes 5 times count++; } while (count <= 5); // Executes once even if condition is false int x = 10; do { System.out.println("Executes once: " + x); // βœ… Prints once! } while (x < 5); // Condition false, but body already ran // Real-world: Menu system java.util.Scanner scanner = new java.util.Scanner(System.in); int choice; do { System.out.println("\n=== Menu ==="); System.out.println("1. View"); System.out.println("2. Add"); System.out.println("3. Delete"); System.out.println("0. Exit"); System.out.print("Choice: "); choice = scanner.nextInt(); switch (choice) { case 1: System.out.println("Viewing..."); break; case 2: System.out.println("Adding..."); break; case 3: System.out.println("Deleting..."); break; case 0: System.out.println("Goodbye!"); break; default: System.out.println("Invalid!"); } } while (choice != 0); // Menu always shows once // Real-world: Input validation int age; do { System.out.print("Enter age (1-120): "); age = scanner.nextInt(); } while (age < 1 || age > 120); // Repeat until valid System.out.println("Valid age: " + age); // Real-world: Password attempt String password; int attempts = 0; do { System.out.print("Enter password: "); password = scanner.next(); attempts++; } while (!password.equals("secret") && attempts < 3); if (password.equals("secret")) { System.out.println("βœ… Access granted"); } else { System.out.println("❌ Too many attempts"); } // Generating random number until condition met java.util.Random random = new java.util.Random(); int roll; do { roll = random.nextInt(6) + 1; // 1-6 System.out.println("Rolled: " + roll); } while (roll != 6); // Keep rolling until 6 System.out.println("Got a 6!"); } }

⚠️ Common Mistakes

Mistake #1: Forgetting semicolon

java
do { System.out.println("Hello"); } while (condition) // ❌ Missing semicolon! // Correct: while (condition);

Mistake #2: Assuming it checks before first iteration

java
int x = 10; do { System.out.println(x); // βœ… Prints 10! } while (x < 5); // Even though condition is false // If you want to check first, use while: while (x < 5) { // ❌ Doesn't execute System.out.println(x); }

Mistake #3: Infinite loop

java
int i = 0; do { System.out.println(i); // ❌ Forgot to update i! } while (i < 5); // Infinite loop

Mistake #4: Using when while is better

java
// ❌ Unnecessary do-while do { // Process only if file exists } while (fileExists); // βœ… Use while if first execution isn't guaranteed while (fileExists) { // Process }

5. The Comparison & Decision Layer

do-while vs while

Aspectdo-whilewhile
Execution guaranteeβœ… At least once⚠️ May be 0 times
Condition checkAfter bodyBefore body
Use caseMenus, validationFile reading, polling
Semicolonβœ… Required❌ Not used
ExampleMenu displaywhile (hasData)

Decision Tree

graph TD Start{Need guaranteed<br/>first execution?} Start -- Yes --> DoWhile["Use do-while"] Start -- No --> While["Use while"] DoWhile --> Examples["- Menus<br/>- Input validation<br/>- 'Try once' logic"] While --> Examples2["- File reading<br/>- Polling<br/>- May skip entirely"] style DoWhile fill:#2E7D32

6. The "Interview Corner" (The Edge)

πŸ† Interview Question #1: "What's the key difference from while?"

Answer: Execution guarantee:

  • do-while: Always executes at least once (exit-controlled)
  • while: May execute zero times (entry-controlled)
java
int x = 10; do { print(x); } while (x < 5); // Prints once while (x < 5) { print(x); } // Never prints

πŸ† Interview Question #2: "When to use do-while?"

Answer: When first execution is mandatory:

  1. Menu systems β€” must show menu once
  2. Input validation β€” ask for input, then validate
  3. "Try-then-check" β€” attempt action, check success

If execution can be skipped based on initial condition, use while instead.

πŸ† Interview Question #3: "Why the semicolon?"

Answer: Syntactic consistency. The while(condition); is a complete statement marking the end of the loop. Without it, Java wouldn't know where the loop ends:

java
do { // body } while (condition); // βœ… Statement terminator

πŸ’‘ Pro Tips

Tip #1: Perfect for menus

java
int choice; do { displayMenu(); choice = getInput(); processChoice(choice); } while (choice != EXIT);

Tip #2: Input validation pattern

java
int value; do { System.out.print("Enter positive number: "); value = scanner.nextInt(); } while (value <= 0); // Guaranteed to ask at least once

Tip #3: Add attempt limit

java
int attempts = 0; do { tryConnect(); attempts++; } while (!connected && attempts < MAX);

πŸ“š Real-World Examples

ATM Menu: Show options, repeat until exit
Game Loop: Play round, ask "Play again?"
Validation: Enter password, check validity
Dice Games: Roll until target number


πŸŽ“ Key Takeaways

βœ… Exit-controlledβ€”checks condition after execution
βœ… Guarantees at least one iteration
βœ… Requires semicolon after while
βœ… Best for menus and input validation
βœ… Use while if first execution isn't guaranteed

Final Tip: If you need "do this once, then maybe repeat", choose do-while!

Topics Covered

Java FundamentalsControl Flow

Tags

#java#control-flow#loops#conditionals#if-else#switch#beginner-friendly

Last Updated

2025-02-01