Card 07/ 08

ExerciseDifficulty: Intermediate1 min

Four Loops Over One Array: Which Throws, and Which Lies

One array of five elements, four loops over it. For each, decide whether it visits all five, visits too few, or throws — and on which pass. Write all four down before opening the reveal.

java
String[] xs = {"a", "b", "c", "d", "e"};

for (int i = 0; i < xs.length; i++) { System.out.print(xs[i]); }
for (int i = 0; i <= xs.length; i++) { System.out.print(xs[i]); }
for (int i = 1; i < xs.length; i++) { System.out.print(xs[i]); }
for (String x : xs) { System.out.print(x); }
What each of the four loops does
Each loop, what it prints, and what went wrong
LoopPrintsVerdict
i = 0; i < lengthabcdeCorrect, and the form to write by default
i = 0; i <= lengthabcde then throwsReaches index 5, which does not exist
i = 1; i < lengthbcdeSilently drops the first element and never complains
for (String x : xs)abcdeCorrect, and cannot be off by one at all

The third is the dangerous one. It runs, it produces output, and the output is missing something — which is a bug that reaches a user rather than a stack trace that reaches you.

The fourth has no index to get wrong, which is why it is the right default. Reach for a counted loop only when you actually need the position.