Card 03/ 08

ExampleDifficulty: Beginner1 min

Zero-Based Indexes Example: Why the Last of Seven Is Index 6

Seven slots, and the highest number you may put in the brackets is six.

An array holds a fixed number of values of one type, reached by position, and Java array indexes start at 0, so an array of length 7 has indexes 0 to 6. The index is an offset, how far a slot sits from the start, not a count of items. Seven days of the week:

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 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

Counting from zero is not a Java quirk. C, JavaScript and Python index the same way, because the index is what the machine adds to the start of the array to find a slot.

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.