AP® Computer Science A · Unit 4 · Topic 4.3

Creating an Array and Indexing from Zero

An array is one variable name holding a fixed number of values in a row, each reachable instantly by an index. Indexing starts at 0 because an index counts how far a slot sits from the start, not its position in line.

A single variable can only hold one value, so storing a hundred scores would normally mean a hundred names. An array solves this by reserving one block of memory sliced into equal-sized slots, all under one name, each slot holding one value of the same type. You reach any slot instantly with an index in square brackets, like scores[3], instead of needing a different variable for every value.

This works because the array stores its elements contiguously, back to back in memory. Once Java knows where the array starts and how big each slot is, it can jump straight to any element by adding the index to the starting position — no searching, no stepping through the others first. That's why indexing is a single, fast step no matter how large the array is.

The index is really an offset: how many slots over from the first one. The first element needs 0 slots of movement to reach itself, so it lives at index 0, and an array of length 5 fills indices 0 through 4 — the last legal index is always length - 1, not length. This offset view of indexing carries straight into grids in the next topic, where a 2D array needs two offsets, one for row and one for column, to land on a single cell.

Key terms

array
A fixed-size collection of values of the same type, stored contiguously and accessed by index.
index
An offset counting how many slots a given element sits from the first element, starting at 0.
length
The field giving the total number of slots in an array, one more than the last legal index.
ArrayIndexOutOfBoundsException
The error Java throws when code accesses an index less than 0 or greater than length - 1.

Watch it explained

  1. How it worksHow does an array lay elements out in a row so any index is reachable in one step?
  2. Worked exampleTrace int[] a = new int[5]; a[0] = 7; a[4] = 2; and draw the array that results.
  3. How it worksHow does the length field differ from the last legal index of an array?
  4. Common mistakeWhy isn't the first element of an array sitting at index 1?

Check yourself

Your turn1 of 2
int[] a = new int[5]; a[0] = 35; a[4] = 33; What is a[0] + a[4]?

End of topic.