Card 07/ 08
All 8 cards
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.
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
| Loop | Prints | Verdict |
|---|---|---|
i = 0; i < length | abcde | Correct, and the form to write by default |
i = 0; i <= length | abcde then throws | Reaches index 5, which does not exist |
i = 1; i < length | bcde | Silently drops the first element and never complains |
for (String x : xs) | abcde | Correct, 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.