Loops
Loops repeat a block of code while a condition holds. Java offers four looping constructs — for, while, do-while, and the enhanced for-each — plus break and continue for fine-grained control. Choosing the right loop makes code clearer and less error-prone.
The for Loop
The classic for loop bundles initialization, condition, and update into one header. It is ideal when you know the iteration count or need the index.
for (int i = 0; i < 5; i++) {
System.out.print(i + " ");
}
Output:
0 1 2 3 4
All three clauses are optional. for (;;) { ... } is an intentional infinite loop. You can also declare and update multiple variables with commas.
for (int i = 0, j = 10; i < j; i++, j--) {
System.out.println(i + " " + j);
}
The while Loop
A while loop checks its condition before each iteration, so the body may run zero times. Use it when the iteration count is unknown.
int n = 16;
int steps = 0;
while (n > 1) {
n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
steps++;
}
System.out.println("Steps: " + steps); // Steps: 4
Warning: Ensure the loop condition eventually becomes false. A loop whose state never changes runs forever and hangs the program.
The do-while Loop
A do-while checks the condition after the body, guaranteeing at least one execution. It suits input validation and menu loops.
int input;
int attempts = 0;
do {
input = nextSimulatedInput(); // runs at least once
attempts++;
} while (input != 0 && attempts < 3);
The Enhanced for-each Loop
The for-each loop iterates over arrays and any Iterable without manual indexing. It is cleaner and avoids off-by-one errors when you don’t need the index.
String[] langs = {"Java", "Kotlin", "Scala"};
for (String lang : langs) {
System.out.println(lang);
}
int sum = 0;
for (int x : new int[]{10, 20, 30}) {
sum += x;
}
System.out.println(sum); // 60
Note: for-each gives read access to each element but no index, and you cannot modify the underlying collection’s structure during iteration (it throws
ConcurrentModificationException).
break and continue
break exits the nearest loop immediately. continue skips to the next iteration.
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; // skip even numbers
if (i > 7) break; // stop past 7
System.out.print(i + " ");
}
Output:
1 3 5 7
Labeled Breaks
By default break and continue affect only the innermost loop. A label lets you target an outer loop — invaluable for breaking out of nested iteration.
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i * j == 2) {
System.out.println("Found at " + i + "," + j);
break outer; // exits BOTH loops
}
}
}
Output:
Found at 1,2
continue label; similarly jumps to the next iteration of the labeled outer loop.
Tip: Labeled breaks are clearer than flag variables for escaping nested loops, but if you find yourself reaching for them often, consider extracting the inner loop into a method and using
return.
Best Practices
- Use
forwhen you need an index or a known count; use for-each when you just need each element. - Prefer for-each over indexed loops to eliminate off-by-one and bounds errors.
- Keep loop bodies small; extract complex logic into well-named methods.
- Avoid mutating a collection while iterating it — collect changes and apply them after, or use an
Iterator. - Reserve labeled breaks for genuine nested-loop exits; don’t overuse them.