Lesson · Control Flow
Loops: the three forms and what a loop costs
10 min readLoops
for, for-each, while and do-while are four readings of one idea: repeat until a condition says stop. Choosing between them is about intent, and off-by-one is about the boundaries.
The forms and when each is right
A for loop names its three parts on one line: initialise, test, update. That shape is for counting and indexing, and its variable is scoped to the loop. A while loop keeps only the test, for when the repeat is governed by state rather than a counter. A do-while runs the body before the first test, the right shape for retry and input-validation flows.
The enhanced for (for-each) removes the index entirely: for (String name : names). It is the default choice for reading every element of an array or any Iterable, and it eliminates the off-by-one class of bugs on the spot. Reach for an indexed loop only when the position itself matters or the structure changes during iteration.
Loop stepper · for (i = 1; i <= 3; i++)
int sum = 0;
for (int i = 1; i <= 3; i++) {
sum += i;
}
System.out.println(sum);
sum starts at 0. The for statement is next: its three parts run in a fixed order, and the whole loop is just them repeating.
Boundaries: where off-by-one lives
The convention that keeps loops honest: half-open ranges. Iterate i < n rather than i <= n - 1, and the count of iterations equals n by construction. Arrays reward the same discipline: the last valid index is length - 1, and a loop that runs to length is the classic ArrayIndexOutOfBoundsException.
When a loop is off by one, the bug is almost never in the body. Read the boundary aloud: 'while less than, starting at zero, stepping by one' is a sentence that exposes its own mistakes. For loops walking two ends toward each other (two pointers), write the meeting condition once and mean it.
Infinite loops, on purpose and by accident
while (true) is a legitimate construct: server accept loops and event pumps are built on it, exiting through return or break. The accidental version is subtler: a condition that never changes (i < n without i++), a floating-point counter that never quite equals its bound, or an update made on the wrong variable.
Loop variables and floating point: never loop double i = 0; i != 1.0; i += 0.1. The accumulated 0.9999999999999999 never arrives. Accumulate an int and divide at the point of use instead.
What a loop actually costs
The JIT is very good at loops: it compiles hot ones to native code, unrolls small fixed counts, and can eliminate bounds checks it can prove redundant. The costs that remain are yours: work inside the loop that could be hoisted out (a method call producing a constant, a regex compiled per iteration, string concatenation), and data structures whose traversal is cache-hostile.
The classic micro-rule with real backing: call array.length freely, the JIT treats it as a constant for a non-escaping array. Spend the effort on algorithmic complexity instead. A loop inside a loop is 500,000 steps at n = 1000, and no unrolling rescues a quadratic.
for-each iterates a snapshot of the list variable, not the object
Adding or removing elements while for-each walks a collection throws ConcurrentModificationException on the next step (except through the iterator itself). The enhanced for hides the iterator from you, so structural changes inside the loop are a bug almost every time. Use removeIf, or an explicit Iterator, when the loop must modify what it walks.
Interview angles
When do you choose while over for?+
When repetition is governed by state rather than a counter: reading until a sentinel, retrying until success, consuming a queue until empty. for declares counting loops; while declares condition loops. do-while is for bodies that must run at least once.
Why prefer for-each over an indexed loop?+
It removes index bookkeeping and its off-by-one failures, and it works uniformly across arrays and every Iterable. Use an indexed loop only when the position is needed or the collection changes during iteration.
What is the half-open range convention?+
Write bounds as start inclusive, end exclusive: i < n, first to length. The number of iterations is then n minus start with no arithmetic to check, and the same discipline maps onto subList, substring and slice-style APIs.