for and while Loops
Java's three loop forms, when to reach for each one, and how break and continue control them.
2 min read
Java gives you three loop constructs, and picking the right one for a given job makes the intent of your code obvious at a glance.
The classic for loop
Best when you know how many times you're iterating, or need an index:
for (int i = 0; i < 5; i++) {
System.out.println("Count: " + i);
}The three parts — initialization, condition, update — run in a fixed order: initialize once, check the condition, run the body, run the update, check the condition again, and so on until the condition is false.
The enhanced for loop (for-each)
When you just need each element of a collection or array, without caring about the index, the for-each form is clearer:
int[] numbers = {10, 20, 30};
for (int n : numbers) {
System.out.println(n);
}Read for (int n : numbers) as "for each n in numbers". You lose the ability to modify the underlying collection's structure or access the index directly, but for simple iteration, it removes an entire class of off-by-one bugs.
while and do-while
while checks its condition before each iteration, so the body might not run at all:
int attempts = 0;
while (attempts < 3) {
System.out.println("Attempt " + attempts);
attempts++;
}do-while checks after the body runs, guaranteeing at least one execution — useful for things like "prompt the user, then keep prompting until the input is valid":
int input;
do {
input = getUserInput();
} while (input < 0);break and continue
break exits the loop entirely; continue skips to the next iteration without exiting.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // stop looping entirely once i hits 5
}
if (i % 2 == 0) {
continue; // skip even numbers, keep looping
}
System.out.println(i); // prints 1, 3
}Choosing between them
- Reach for the classic for loop when you need an index or a counter with custom step logic.
- Reach for for-each when you're just processing every element of a collection — it's the most common loop in real Java code.
- Reach for while when the number of iterations isn't known ahead of time and depends on some condition changing.
- Reach for do-while only in the specific case where the body must run at least once regardless of the condition.
Getting comfortable with all four control-flow tools (including switch from the previous lesson) means you're rarely forcing the wrong shape of loop onto a problem.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.