What is a While Loop?
A while loop repeats a block of code as long as a condition is true. Unlike a for loop, you use a while loop when the number of iterations is not known in advance.
java
while (condition) {
// Code to execute
// Must update condition to avoid infinite loop
}Basic While Loop
java
public class WhileDemo {
public static void main(String[] args) {
int count = 1;
while (count <= 5) {
System.out.println("Count: " + count);
count++;
}
}
}Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5Do-While Loop
The do-while loop executes the code block at least once before checking the condition:
java
do {
// Code executes at least once
} while (condition);java
import java.util.Scanner;
public class MenuSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\n=== Menu ===");
System.out.println("1. Say Hello");
System.out.println("2. Say Goodbye");
System.out.println("3. Exit");
System.out.print("Enter choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1 -> System.out.println("Hello!");
case 2 -> System.out.println("Goodbye!");
case 3 -> System.out.println("Exiting...");
default -> System.out.println("Invalid choice!");
}
} while (choice != 3);
scanner.close();
}
}While vs Do-While vs For
| Feature | while | do-while | for |
|---|---|---|---|
| Condition check | Before loop body | After loop body | Before loop body |
| Min executions | 0 | 1 | 0 |
| Best for | Unknown iterations | Must run at least once | Known iterations |
Practical Example: Number Guessing Game
java
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int secret = random.nextInt(100) + 1;
int guess;
int attempts = 0;
System.out.println("I'm thinking of a number between 1 and 100.");
do {
System.out.print("Your guess: ");
guess = scanner.nextInt();
attempts++;
if (guess < secret) {
System.out.println("Too low! Try again.");
} else if (guess > secret) {
System.out.println("Too high! Try again.");
}
} while (guess != secret);
System.out.printf("Correct! You guessed it in %d attempts.%n", attempts);
scanner.close();
}
}Infinite Loop with While
java
// Common pattern for servers, game loops
while (true) {
// Process requests...
if (shouldStop) break;
}Summary
whileloops repeat while a condition is true — condition checked before each iterationdo-whileloops guarantee at least one execution — condition checked after- Use
whilewhen iterations are unknown; useforwhen iterations are known - Always ensure the loop condition eventually becomes
falseto avoid infinite loops do-whileis ideal for menu systems and input validation