Card 03/ 08

ExampleDifficulty: Beginner1 min

Why the Last Index of a Seven-Slot Array Is Six

Seven slots, and the highest number you may put in the brackets is six. It reads like a mistake until you see what the number means.

java
String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};

System.out.println(days.length);
System.out.println(days[0]);
System.out.println(days[6]);
text
7
Mon
Sun

The index is not a count of items. It is an offset — how far from the start this slot sits. The first slot is zero away from the start, which is what makes it days[0], and the seventh is six away.

Position, index and offset in a seven-element array
Which oneIndexDistance from the start
First00 slots
Second11 slot
Seventh66 slots

length counts and the index measures, so they are never the same number for the last element. The pair you will write for the rest of your life is 0 to length - 1.