Loops
A loop repeats a block while a condition holds, or once for each element of a collection. Java has while, do-while, for, and the enhanced for.
Detailed Explanation
You use a loop when the same work must run for many items or until a condition changes. Reading lines, summing an array, retrying a request, and walking a list are all loops. The condition is a boolean, the same rule as if. If you write a condition that never becomes false, the loop never stops.
while (cond) { ... } tests first. If cond is already false, the body never runs. do { ... } while (cond); runs the body once, then tests. Use do-while when the body must produce the value you are testing, such as reading the first menu choice.
The classic for (init; cond; step) is a while with the counter declared and updated in one place. init runs once. cond runs before each iteration. step runs after each body. Leaving parts empty is legal (for (;;)) and is an infinite loop you must break.
The enhanced for (for (Item item : items)) walks an array or an Iterable. It does not give you the index. It does not let you add or remove from a collection during iteration (an iterator's remove is the safe way). It is the default when you only need the elements.
break leaves the innermost loop, or a labelled loop if you name it. continue skips to the next iteration. Labels are rare and usually mean the loops should be a method. Streams (list.stream().map(...)) replace some loops with a pipeline; they are not faster by default, but they make the transformation obvious when there is no need for an index or a break.
You reach for while when the end condition is not a counter. You reach for classic for when you need an index or a sliding window. You reach for enhanced for when you need each element once. You avoid looping by hand over a LinkedList with get(i), because each get is O(n) and the whole loop becomes O(n²).
The costs are off-by-one errors, accidental infinite loops, and mutation during iteration. Count with i < length, not i <= length, on zero-based arrays. Update the condition inside while or the loop never ends. Prefer the enhanced for or an iterator so you do not invent a broken index.
Code Examples
public class Sums {
static int sum(int[] xs) {
int total = 0;
for (int x : xs) { // enhanced for: no index needed
total += x;
}
return total;
}
static int indexOf(int[] xs, int target) {
for (int i = 0; i < xs.length; i++) { // classic for: we need the index
if (xs[i] == target) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
int[] xs = {2, 4, 6};
System.out.println(sum(xs)); // prints: 12
System.out.println(indexOf(xs, 4)); // prints: 1
}
}public class Retry {
static int attempts = 0;
static boolean ready() {
attempts++;
return attempts >= 3;
}
public static void main(String[] args) {
int n = 0;
while (!ready()) { // test first; body runs until ready() is true
n++;
}
System.out.println(n); // prints: 2
System.out.println(attempts); // prints: 3
}
}Common Gotchas
`list.get(i)` inside a loop over `LinkedList` is O(n²)
use the enhanced `for` or an iterator.
Mutating a collection while using enhanced `for` throws
`ConcurrentModificationException` appears on the next iteration. Use `Iterator.remove` or iterate a copy.
`for (int i = 0; i <= xs.length; i++)` reads one past the end
the last legal index is `length - 1`.
`do-while` always runs once
that is the feature. Do not use it when an empty input should skip the body.