The while loop runs as long as a condition is true. Unlike for (which iterates a known number of times), while is used when you do not know how many iterations are needed — like retrying a flaky action until it succeeds.
public class WhileBasics {
public static void main(String[] args) {
// Simulate retrying a failed test action
int attempts = 0;
int maxAttempts = 3;
boolean success = false;
while (!success && attempts < maxAttempts) {
attempts++;
System.out.println("Attempt " + attempts);
// Simulate: succeeds on 3rd try
if (attempts == 3) {
success = true;
}
}
if (success) {
System.out.println("Action succeeded after " + attempts + " attempts");
} else {
System.out.println("Action failed after " + maxAttempts + " attempts");
}
}
}Attempt 1
Attempt 2
Attempt 3
Action succeeded after 3 attempts| Use for when | Use while when |
|---|---|
| Number of iterations is known | Number of iterations is unknown |
| Iterating through arrays/collections | Waiting for a condition to change |
| Counting from A to B | Retrying until success or timeout |
| Processing each element | Reading until end of input |
A do-while loop runs the body at least once, then checks the condition. Use it when the action must execute before you can evaluate whether to continue.
public class DoWhile {
public static void main(String[] args) {
// Menu-driven test runner
int choice = 0;
do {
choice++;
System.out.println("Running test suite #" + choice);
} while (choice < 3);
System.out.println("All suites complete");
// Practical: generate test IDs
int id = 1000;
do {
System.out.println("TC-" + id);
id++;
} while (id <= 1003);
}
}public class InfiniteLoop {
public static void main(String[] args) {
// Intentional infinite loop with break condition
int count = 0;
while (true) {
count++;
System.out.println("Polling... attempt " + count);
if (count >= 5) {
System.out.println("Max polls reached, exiting");
break;
}
}
// Common ACCIDENT — forgetting to update the loop variable
// int i = 0;
// while (i < 5) {
// System.out.println(i);
// // i++ is missing — loops forever!
// }
}
}Forgetting to update the loop variable in a while loop causes an infinite loop. Unlike for loops where the update is in the header, while loops require you to update the variable inside the body.
public class SumAverage {
public static void main(String[] args) {
int[] scores = {85, 92, 78, 96, 88};
int sum = 0;
int i = 0;
while (i < scores.length) {
sum += scores[i];
i++;
}
double average = (double) sum / scores.length;
System.out.println("Total: " + sum); // 439
System.out.printf("Average: %.1f%n", average); // 87.8
}
}Q: What is the difference between while and do-while?
A: A while loop checks the condition BEFORE executing the body — if the condition is false initially, the body never runs. A do-while loop executes the body FIRST, then checks the condition — the body runs at least once regardless of the condition. Use do-while when the action must happen before you can evaluate whether to repeat it.
Exercise 1: Write a while loop that reverses a number. Input: 12345 → Output: 54321. (Hint: use % 10 to get the last digit, and / 10 to remove it.)
Exercise 2: Write a program that keeps doubling a number starting from 1 until it exceeds 1000. Print each step.