Grade 11 Computer Science · Arrays

A length settled at the moment of creation

What is got in exchange for giving up growth.

A structure that gives up growing, on purpose

A list in Python grows as much as needed, and an array in Java will not grow by even one cell. That sounds like a step backwards, but thanks to it the millionth cell is reached as fast as the first. And there is another surprise: at the moment of creation every cell is already full — even the ones you never wrote to.

A list in Python grows as much as needed. An array in Java does not grow at all: at the moment of creation one settles how many cells it will have, and that number does not change until the array is discarded. That sounds like a step backwards, and it has an exact return.

The cells are numbered from zero, and the last position is the length minus one.
int[] scores = new int[4];       // four cells, all zero
String[] names = new String[3];  // three cells, all empty

scores[0] = 88;
scores[3] = 91;
System.out.println(scores.length);   // 4 — a field, not a call
System.out.println(scores[1]);       // 0 — never assigned

The value already sitting there

A surprising detail: immediately on creation all the cells are already full. In an array of whole numbers they are all zero, in booleans all false, and in reference types all an empty value — not an empty string, but the absence of an arrow. That last distinction matters, because an array of strings created and not filled is a trap: any attempt to ask something of a cell not written to will fall at run time. This is the same advice from the unit on constructors — initialise everything at once and do not rely on “it will fill later”.

Kind of arrayThe initial value in each cell
Whole numbersZero
BooleansFalse
Reference typesThe absence of an arrow

Example 1 — why access to the millionth is as fast as the first

  1. All the cells are in one run.
  2. The size of each is known.
  3. So one can compute directly where.

Example 2 — why an empty string array is dangerous

  1. The cells hold the absence of an arrow.
  2. That is not an empty string.
  3. And any question about it falls.
A question about names[0], for example names[0].length(), would fall at run time: there is no arrow to follow.