Card 07/ 08
Practice: Which Array Loops Throw or Skip an Element
Four loops over five elements: one throws, one silently drops one, two are correct.
Valid indexes run from 0 to length - 1, and a for-each loop has no index to get wrong. For each of the four loops below, decide whether it visits all five elements, visits too few, or throws, and on which pass. Write all four down before opening the answer.
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: 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 need the position.
← → move through sections and cards