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.
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 assignedThe 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 array | The initial value in each cell |
|---|---|
| Whole numbers | Zero |
| Booleans | False |
| Reference types | The absence of an arrow |
Example 1 — why access to the millionth is as fast as the first
- All the cells are in one run.
- The size of each is known.
- So one can compute directly where.
Example 2 — why an empty string array is dangerous
- The cells hold the absence of an arrow.
- That is not an empty string.
- And any question about it falls.