while Loops vs for Loops: When to Use Which
You'll learn when to choose a while loop over a for loop based on whether you know how many iterations you need in advance.
The Core Difference
Both while and for loops repeat code, but they shine in different situations:
- Use
whilewhen you don't know how many times you'll loop — the number of iterations depends on changing conditions, user input, or data that arrives during execution. - Use
forwhen you know the iteration count or range in advance — you're counting through numbers, processing array elements, or repeating something a fixed number of times.
Think of It This Way
A while loop is like waiting for a pot of water to boil: you keep checking (looping) until the condition is met, but you don't know exactly when that'll be.
A for loop is like climbing stairs in a building: you know there are 10 steps, so you count from 1 to 10.
Classic Examples
while loop — reading user input until they type "quit":
String input = "";
while (!input.equals("quit")) {
// process input
// get next input
}
for loop — counting from 1 to 10:
for (int i = 1; i <= 10; i++) {
// do something 10 times
}
When in Doubt
If your loop has a counter variable that changes predictably each iteration, prefer for. If your loop depends on unpredictable conditions (user actions, data validation, searching), choose while.
Key Takeaway: Use while for indefinite iteration (unknown repetition count); use for for definite iteration (known range or count). Choose the loop that makes your intent clearest.