πŸ“ What You’ll Learn

  • How the while loop works
  • How the do...while loop works
  • Differences between the two
  • Common patterns and pitfalls
  • Real-world examples

πŸ”„ What is a While Loop?

A while loop keeps running as long as its condition is true.

πŸ”§ Syntax:

while (condition) {
    // code to repeat
}

βœ… Example

int i = 1;

while (i <= 5) {
    System.out.println("i = " + i);
    i++;
}

πŸ” This prints i = 1 through i = 5.

πŸ”‚ The do...while Loop

This version always runs at least once β€” because the condition is checked after the first execution.

πŸ”§ Syntax:

do {
    // code to run
} while (condition);

Example:

int i = 1;

do {
    System.out.println("i = " + i);
    i++;
} while (i <= 5);

πŸ” When to Use Which?

Use this... When...
while You may want to skip the loop entirely
do...while You always want it to run at least once

⚠️ Common Mistakes

  • Forgetting to update the loop variable (infinite loop!)
  • Misplacing semicolons:
    while (i < 5); // ❌ Don't do this
  • Using assignment instead of comparison:
    while (x = 5) // ❌ should be while (x == 5)

πŸ›  Real-Life Example

Password Retry Simulation:

Scanner scanner = new Scanner(System.in);
String password;

do {
    System.out.print("Enter password: ");
    password = scanner.nextLine();
} while (!password.equals("java123"));

System.out.println("Access granted!");

πŸ“˜ Recap

  • while loops check condition before running
  • do...while loops run at least once
  • Be careful with infinite loops and condition logic