Introduction
Imagine you're at a pizza party where you get to keep eating slices until you're completely full. You eat at least one slice (because who can resist pizza?), then check if you want more. That's exactly how a do-while loop works in Javaβit guarantees the code runs at least once before checking the condition!
Unlike regular while loops that might never execute, do-while loops are like that enthusiastic friend who always shows up to the party first and then decides if they want to stay longer.
What is a Do-While Loop?
A do-while loop is a post-test loop that executes a block of code first, then checks a condition to determine if it should repeat. This "do first, check later" behavior makes it perfect for situations where you need to guarantee at least one execution.
Key Characteristics:
- β Guaranteed execution: Runs at least once
- β Post-test evaluation: Condition checked after execution
- β
Syntax:
do { code } while (condition); - β
Semicolon required: Don't forget the
;afterwhile(condition)
Code Explanation with Examples
Example 1: Basic Do-While vs While Loop
public class BasicDoWhile {
public static void main(String[] args) {
int count = 5;
System.out.println("=== WHILE LOOP (may not execute) ===");
// β While loop - might not run at all
while (count < 3) {
System.out.println("While loop count: " + count);
count++;
}
System.out.println("While loop finished. Count is: " + count);
// Reset count
count = 5;
System.out.println("\n=== DO-WHILE LOOP (always executes once) ===");
// β
Do-while loop - always runs at least once
do {
System.out.println("Do-while count: " + count);
count++;
} while (count < 3);
System.out.println("Do-while finished. Count is: " + count);
}
}
Output:
=== WHILE LOOP (may not execute) === While loop finished. Count is: 5 === DO-WHILE LOOP (always executes once) === Do-while count: 5 Do-while finished. Count is: 6
Explanation: Even though count = 5 doesn't satisfy count < 3, the do-while loop still executes once because the condition is checked AFTER the code block runs.
Example 2: User Input Validation
import java.util.Scanner;
public class UserInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
System.out.println("=== NUMBER VALIDATION ===");
// Perfect use case: we need to get input AT LEAST once
do {
System.out.print("Enter a positive number: ");
number = scanner.nextInt();
if (number <= 0) {
System.out.println("Invalid input! Number must be positive.");
}
} while (number <= 0); // Keep asking until we get valid input
System.out.println("Thank you! You entered: " + number);
// Another example: menu system
int choice;
do {
System.out.println("\n=== MENU ===");
System.out.println("1. Play Game");
System.out.println("2. View Scores");
System.out.println("3. Exit");
System.out.print("Enter your choice (1-3): ");
choice = scanner.nextInt();
switch (choice) {
case 1 -> System.out.println("Starting game...");
case 2 -> System.out.println("Displaying scores...");
case 3 -> System.out.println("Goodbye!");
default -> System.out.println("Invalid choice! Please try again.");
}
} while (choice != 3); // Continue until user chooses to exit
scanner.close();
}
}
Sample Output:
=== NUMBER VALIDATION === Enter a positive number: -5 Invalid input! Number must be positive. Enter a positive number: 0 Invalid input! Number must be positive. Enter a positive number: 42 Thank you! You entered: 42 === MENU === 1. Play Game 2. View Scores 3. Exit Enter your choice (1-3): 4 Invalid choice! Please try again. === MENU === 1. Play Game 2. View Scores 3. Exit Enter your choice (1-3): 1 Starting game... === MENU === 1. Play Game 2. View Scores 3. Exit Enter your choice (1-3): 3 Goodbye!
Example 3: Mathematical Calculations
public class MathExamples {
public static void main(String[] args) {
System.out.println("=== COUNTDOWN EXAMPLE ===");
int countdown = 3;
do {
System.out.println("Countdown: " + countdown);
countdown--;
} while (countdown > 0);
System.out.println("Blast off! π");
System.out.println("\n=== SUM CALCULATION ===");
int number = 1;
int sum = 0;
// Sum numbers from 1 to 5
do {
sum += number;
System.out.println("Added " + number + ", total: " + sum);
number++;
} while (number <= 5);
System.out.println("Final sum: " + sum);
System.out.println("\n=== FACTORIAL CALCULATION ===");
int factorialNumber = 5;
long factorial = 1;
int current = 1;
do {
factorial *= current;
System.out.println(current + "! = " + factorial);
current++;
} while (current <= factorialNumber);
System.out.println("Final result: " + factorialNumber + "! = " + factorial);
}
}
Output:
=== COUNTDOWN EXAMPLE === Countdown: 3 Countdown: 2 Countdown: 1 Blast off! π === SUM CALCULATION === Added 1, total: 1 Added 2, total: 3 Added 3, total: 6 Added 4, total: 10 Added 5, total: 15 Final sum: 15 === FACTORIAL CALCULATION === 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 Final result: 5! = 120
Example 4: Real-World Practical Scenarios
import java.util.Random;
public class RealWorldScenarios {
public static void main(String[] args) {
Random random = new Random();
System.out.println("=== GAME: ROLL UNTIL YOU WIN ===");
int diceRoll;
int attempts = 0;
// Keep rolling until we get a 6
do {
diceRoll = random.nextInt(6) + 1; // 1-6
attempts++;
System.out.println("Attempt " + attempts + ": Rolled a " + diceRoll);
} while (diceRoll != 6);
System.out.println("π You won after " + attempts + " attempts!");
System.out.println("\n=== PASSWORD GENERATOR ===");
String password;
boolean hasUpperCase;
// Generate passwords until we get one with uppercase letter
do {
password = generateRandomPassword();
hasUpperCase = !password.equals(password.toLowerCase());
System.out.println("Generated: " + password +
(hasUpperCase ? " β" : " β (no uppercase)"));
} while (!hasUpperCase);
System.out.println("β
Valid password: " + password);
System.out.println("\n=== BANK TRANSACTION SIMULATION ===");
double balance = 1000.0;
double withdrawalAmount;
java.util.Scanner scanner = new java.util.Scanner(System.in);
do {
System.out.printf("Current balance: $%.2f%n", balance);
System.out.print("Enter withdrawal amount (0 to exit): $");
withdrawalAmount = scanner.nextDouble();
if (withdrawalAmount > 0) {
if (withdrawalAmount <= balance) {
balance -= withdrawalAmount;
System.out.printf("Withdrew $%.2f. New balance: $%.2f%n",
withdrawalAmount, balance);
} else {
System.out.println("Insufficient funds!");
}
}
} while (withdrawalAmount != 0 && balance > 0);
System.out.printf("Final balance: $%.2f%n", balance);
scanner.close();
}
public static String generateRandomPassword() {
String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuilder password = new StringBuilder();
for (int i = 0; i < 8; i++) {
password.append(chars.charAt(random.nextInt(chars.length())));
}
return password.toString();
}
}
Sample Output:
=== GAME: ROLL UNTIL YOU WIN === Attempt 1: Rolled a 3 Attempt 2: Rolled a 2 Attempt 3: Rolled a 6 π You won after 3 attempts! === PASSWORD GENERATOR === Generated: a7b3c9de β (no uppercase) Generated: k8mL2npQ β β Valid password: k8mL2npQ === BANK TRANSACTION SIMULATION === Current balance: $1000.00 Enter withdrawal amount (0 to exit): $200 Withdrew $200.00. New balance: $800.00 Current balance: $800.00 Enter withdrawal amount (0 to exit): $500 Withdrew $500.00. New balance: $300.00 Current balance: $300.00 Enter withdrawal amount (0 to exit): $0 Final balance: $300.00
Example 5: Nested Do-While Loops
public class NestedDoWhile {
public static void main(String[] args) {
System.out.println("=== MULTIPLICATION TABLE ===");
int i = 1;
// Outer loop - rows
do {
int j = 1;
System.out.print("Table of " + i + ": ");
// Inner loop - columns
do {
System.out.print((i * j) + "\t");
j++;
} while (j <= 5);
System.out.println(); // New line after each row
i++;
} while (i <= 3);
System.out.println("\n=== PATTERN PRINTING ===");
int rows = 1;
int maxRows = 4;
do {
int stars = 1;
System.out.print("Row " + rows + ": ");
// Print stars for current row
do {
System.out.print("* ");
stars++;
} while (stars <= rows);
System.out.println();
rows++;
} while (rows <= maxRows);
System.out.println("\n=== STUDENT GRADE SYSTEM ===");
java.util.Scanner scanner = new java.util.Scanner(System.in);
char continueGrading;
do {
// Process one student
System.out.print("Enter student name: ");
String name = scanner.nextLine();
int subjectCount = 1;
double totalMarks = 0;
int subjects;
System.out.print("How many subjects? ");
subjects = scanner.nextInt();
if (subjects > 0) {
do {
System.out.print("Enter marks for subject " + subjectCount + ": ");
double marks = scanner.nextDouble();
totalMarks += marks;
subjectCount++;
} while (subjectCount <= subjects);
double average = totalMarks / subjects;
System.out.printf("Student: %s, Average: %.2f, Grade: %s%n",
name, average, getGrade(average));
}
scanner.nextLine(); // Clear buffer
System.out.print("Process another student? (y/n): ");
continueGrading = scanner.nextLine().charAt(0);
} while (continueGrading == 'y' || continueGrading == 'Y');
System.out.println("Grading completed!");
scanner.close();
}
public static String getGrade(double average) {
if (average >= 90) return "A";
if (average >= 80) return "B";
if (average >= 70) return "C";
if (average >= 60) return "D";
return "F";
}
}
Output:
=== MULTIPLICATION TABLE === Table of 1: 1 2 3 4 5 Table of 2: 2 4 6 8 10 Table of 3: 3 6 9 12 15 === PATTERN PRINTING === Row 1: * Row 2: * * Row 3: * * * Row 4: * * * * === STUDENT GRADE SYSTEM === Enter student name: Alice How many subjects? 3 Enter marks for subject 1: 85 Enter marks for subject 2: 92 Enter marks for subject 3: 78 Student: Alice, Average: 85.00, Grade: B Process another student? (y/n): y Enter student name: Bob How many subjects? 2 Enter marks for subject 1: 95 Enter marks for subject 2: 88 Student: Bob, Average: 91.50, Grade: A Process another student? (y/n): n Grading completed!
Example 6: Common Pitfalls and Best Practices
public class PitfallsAndBestPractices {
public static void main(String[] args) {
System.out.println("=== COMMON PITFALLS ===");
// β PITFALL 1: Infinite loops
/*
int x = 1;
do {
System.out.println("This will run forever!");
// Forgot to increment x - infinite loop!
} while (x <= 5);
*/
// β
SOLUTION: Always update loop control variable
int x = 1;
do {
System.out.println("Controlled loop - iteration: " + x);
x++; // Important: update the variable
} while (x <= 3);
// β PITFALL 2: Missing semicolon
/*
int y = 1;
do {
System.out.println("Missing semicolon");
y++;
} while (y <= 3) // β Compilation error - missing ;
*/
// β
SOLUTION: Always include semicolon
int y = 1;
do {
System.out.println("Correct syntax - iteration: " + y);
y++;
} while (y <= 3); // β
Semicolon required
// β PITFALL 3: Using = instead of ==
int z = 1;
System.out.println("\nβ οΈ Watch out for assignment in condition:");
do {
System.out.println("z = " + z);
z++;
} while (z = 3); // β This would be compilation error in Java
// (shown here for demonstration)
// β
SOLUTION: Use == for comparison
int a = 1;
do {
System.out.println("Correct comparison - a = " + a);
a++;
} while (a == 3); // β
Proper comparison
System.out.println("\n=== BEST PRACTICES ===");
// β
GOOD: Clear loop control variable names
int userAttempts = 0;
final int MAX_ATTEMPTS = 3;
boolean validInput = false;
do {
userAttempts++;
System.out.println("Attempt " + userAttempts + " of " + MAX_ATTEMPTS);
// Simulate some validation
if (userAttempts == 2) {
validInput = true;
System.out.println("Input validated successfully!");
}
} while (!validInput && userAttempts < MAX_ATTEMPTS);
// β
GOOD: Using break for complex conditions
int counter = 1;
do {
System.out.println("Counter: " + counter);
if (counter == 2) {
System.out.println("Breaking early at counter = 2");
break; // Exit loop early
}
counter++;
} while (counter <= 5);
System.out.println("Loop exited!");
}
}
Output:
=== COMMON PITFALLS === Controlled loop - iteration: 1 Controlled loop - iteration: 2 Controlled loop - iteration: 3 Correct syntax - iteration: 1 Correct syntax - iteration: 2 Correct syntax - iteration: 3 β οΈ Watch out for assignment in condition: z = 1 z = 2 z = 3 Correct comparison - a = 1 === BEST PRACTICES === Attempt 1 of 3 Attempt 2 of 3 Input validated successfully! Counter: 1 Counter: 2 Breaking early at counter = 2 Loop exited!
Example 7: Advanced Do-While Patterns
import java.util.ArrayList;
import java.util.List;
public class AdvancedPatterns {
public static void main(String[] args) {
System.out.println("=== DATA PROCESSING ===");
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
int index = 0;
int sum = 0;
// Process list until condition met
do {
int number = numbers.get(index);
sum += number;
System.out.println("Processed: " + number + ", Running total: " + sum);
index++;
} while (index < numbers.size() && sum < 10); // Stop if sum reaches 10
System.out.println("Final sum: " + sum);
System.out.println("\n=== FILE PROCESSING SIMULATION ===");
boolean fileCorrupted = false;
int retryCount = 0;
final int MAX_RETRIES = 3;
do {
retryCount++;
System.out.println("Attempt " + retryCount + " to process file...");
// Simulate file processing that might fail
boolean processingSuccess = simulateFileProcessing(retryCount);
if (processingSuccess) {
System.out.println("β
File processed successfully!");
fileCorrupted = false;
} else {
System.out.println("β File processing failed");
fileCorrupted = true;
if (retryCount < MAX_RETRIES) {
System.out.println("Retrying...");
} else {
System.out.println("Max retries reached. Giving up.");
}
}
} while (fileCorrupted && retryCount < MAX_RETRIES);
System.out.println("\n=== GAME LOOP SIMULATION ===");
boolean gameRunning = true;
int playerHealth = 100;
int enemyHealth = 80;
do {
System.out.println("\n--- New Round ---");
System.out.println("Player Health: " + playerHealth);
System.out.println("Enemy Health: " + enemyHealth);
// Simulate combat round
int playerDamage = (int) (Math.random() * 20) + 10;
int enemyDamage = (int) (Math.random() * 15) + 5;
enemyHealth -= playerDamage;
playerHealth -= enemyDamage;
System.out.println("Player deals " + playerDamage + " damage");
System.out.println("Enemy deals " + enemyDamage + " damage");
// Check game over conditions
if (playerHealth <= 0) {
System.out.println("π Game Over! You were defeated.");
gameRunning = false;
} else if (enemyHealth <= 0) {
System.out.println("π Victory! Enemy defeated!");
gameRunning = false;
}
} while (gameRunning);
}
public static boolean simulateFileProcessing(int attempt) {
// Simulate: fails on first attempt, succeeds on subsequent attempts
return attempt > 1;
}
}
Output:
=== DATA PROCESSING === Processed: 1, Running total: 1 Processed: 2, Running total: 3 Processed: 3, Running total: 6 Processed: 4, Running total: 10 Final sum: 10 === FILE PROCESSING SIMULATION === Attempt 1 to process file... β File processing failed Retrying... Attempt 2 to process file... β File processed successfully! === GAME LOOP SIMULATION === --- New Round --- Player Health: 100 Enemy Health: 80 Player deals 25 damage Enemy deals 12 damage --- New Round --- Player Health: 88 Enemy Health: 55 Player deals 18 damage Enemy deals 16 damage --- New Round --- Player Health: 72 Enemy Health: 37 Player deals 28 damage Enemy deals 19 damage --- New Round --- Player Health: 53 Enemy Health: 9 Player deals 15 damage π Victory! Enemy defeated!
Do-While vs While vs For Loops
| Feature | While Loop | Do-While Loop | For Loop |
|---|---|---|---|
| When condition checked | Before execution | After execution | Before execution |
| Minimum executions | 0 | 1 | 0 |
| Best for | Unknown iterations | Must run once | Known iterations |
| Syntax | while(cond) { } | do { } while(cond); | for(init;cond;inc) { } |
| Use case | Reading until EOF | Input validation | Iterating arrays |
When to Use Do-While Loops
β Perfect Use Cases:
- User input validation (must ask at least once)
- Menu systems (always show menu first)
- Retry mechanisms (try at least once)
- Game loops (always run one game cycle)
- Initial setup that needs repetition
β Avoid When:
- You might need zero executions
- Working with collections that might be empty
- Simple counter-based iterations (use for-loops instead)
Best Practices
- Always update loop control variables
- Include semicolon after
while(condition) - Use meaningful variable names
- Consider using
breakfor complex exit conditions - Keep loop bodies focused - extract complex logic to methods
- Always test edge cases (first iteration, last iteration)
Common Patterns
public class CommonPatterns {
public static void main(String[] args) {
// Pattern 1: Input validation
java.util.Scanner scanner = new java.util.Scanner(System.in);
int number;
do {
System.out.print("Enter number 1-10: ");
number = scanner.nextInt();
} while (number < 1 || number > 10);
// Pattern 2: Retry with limit
int attempts = 0;
boolean success = false;
do {
attempts++;
success = performOperation();
} while (!success && attempts < 3);
// Pattern 3: Process until sentinel value
int value;
do {
System.out.print("Enter value (-1 to stop): ");
value = scanner.nextInt();
if (value != -1) {
processValue(value);
}
} while (value != -1);
scanner.close();
}
static boolean performOperation() {
// Simulate operation that might fail
return Math.random() > 0.7;
}
static void processValue(int value) {
System.out.println("Processing: " + value);
}
}
Conclusion
Do-While loops are Java's "try at least once" warriors:
- β Guaranteed execution: Always runs the code block at least once
- β Post-test evaluation: Condition checked after execution
- β Perfect for validation: Menus, input checks, retry logic
- β
Clear syntax:
do { } while (condition);structure
Key Takeaways:
- Use when you must execute code at least once
- Great for user input and menu systems
- Don't forget the semicolon after the condition
- Always update loop variables to avoid infinite loops
- Consider break statements for complex exit conditions
Do-while loops are your go-to choice when you need that first attempt guaranteeβmaking them essential for robust, user-friendly Java applications!