Card 03/ 08
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:
String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
System.out.println(days.length);
System.out.println(days[0]);
System.out.println(days[6]);7
Mon
SunThe first slot is zero away from the start, which is what makes it days[0], and the seventh is six away.
| Which one | Index | Distance from the start |
|---|---|---|
| First | 0 | 0 slots |
| Second | 1 | 1 slot |
| Seventh | 6 | 6 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.
← → move through sections and cards