Array Creation and Access
Why the length can never change, why nothing in an array is ever empty, and why the last index is always one less than the count.
- An array stores multiple values of the same type; the values can be either primitive values or object references.
- The length of an array is established at creation and cannot be changed; it is read through the
lengthattribute. newinitializes every element to the default:0for int,0.0for double,falsefor boolean,nullfor a reference type.- An initializer list creates and initializes an array, taking its length from the number of values listed.
arr[i]on the right of=reads the value; on the left it names the slot to modify.- Valid indices are 0 through one less than the length; an index outside that range throws
ArrayIndexOutOfBoundsException. - An out-of-range index throws at run time, not compile time;
tideHeights[6]compiles but throws when the line runs. - Array uses
.lengthwith no brackets, String uses.length(), and ArrayList uses.size(). - For an object array, creating it creates no elements — every slot is
null, so calling a method on a slot is a NullPointerException.
1An Array Is an Object With a Fixed Number of Numbered Slots
A harbor records the water height at the tide gauge once an hour. Six readings, all
double, all the same kind of thing. That is
exactly what an array is for.
An array stores multiple values of the same type. The values can be either primitive values or object references.
double[] tideHeights = new double[6];
That one line does three separate things, and questions are written about the gap between them:
| Part | What it does |
|---|---|
double[] tideHeights | Declares a variable that can hold a reference to an array of double |
new double[6] | Creates the array object itself — six slots, and every one of them filled |
= | Stores the reference to that object in the variable |
The variable holds a reference. The slots live in the object. Everything that is
strange about arrays — aliasing, passing to methods, comparing with
== — follows from that one split, and every diagram in this guide
draws it.
1.1 The Length Is Decided Once
The length of an array is established at the time of creation and
cannot be changed. The length can be accessed through the
length attribute.
new double[6]
makes an object with six slots and no way to make it seven. There is no method that grows it. If
seven readings are needed, a new array of seven is created and the six values are copied across
— the original object is untouched, and the variable is pointed somewhere else.
This is the whole reason ArrayList exists. It is not a better array; it is an object that owns an array and quietly does the make-a-bigger-one-and-copy work whenever it runs out of room.
2Every Slot Is Filled the Moment the Array Exists
When an array is created using the keyword new,
all of its elements are initialized to the default values for the element data
type. The default for int is
0, for
double is
0.0, for
boolean is
false, and for a reference type is
null.
There is no such thing as an empty slot. A brand-new array of six
double already holds six values, all of them
0.0.
| Declaration | Every slot starts as |
|---|---|
new int[4] | 0 |
new double[4] | 0.0 |
new boolean[4] | false |
new String[4] | null |
new Buoy[4] | null — any reference type |
Buoy[] holds no buoysnew Buoy[4]
creates one object: the array. It does not create four buoys. All four slots hold
null, and calling a method on
markers[0] before something is put there is a
NullPointerException.
2.1 Initializer Lists Skip the Default Step
Initializer lists can be used to create and initialize arrays.
double[] tideHeights = {2.1, 2.8, 3.4, 3.9, 3.6, 2.7};
No new, no length in brackets. The length comes
from how many values are listed — six here — and the values go straight in. It ends at
the same place as creating with new and assigning
six times; it just gets there in one line.
{4, 7, 1}
has length 3 and valid indices 0, 1, 2. Counting the values in the braces is usually the first
thing a question needs.
3Reading and Writing a Slot
Square brackets [] are used to access and modify an
element in a 1D array using an index.
double noon = tideHeights[3]; // read slot 3
tideHeights[3] = 4.1; // write slot 3
The same notation does both. On the right of an = it produces the value
in the slot; on the left it names the slot to be overwritten. An element behaves exactly like a
variable of the element type — it can be read, assigned, compared, passed to a method, and
used in arithmetic.
tideHeights[0] = tideHeights[0] + 0.2;
if (tideHeights[2] > tideHeights[1])
{
System.out.println("still rising");
}
4The Index Range, and What Happens Outside It
The valid index values for an array are 0 through one less than the length,
inclusive. Using an index outside that range results in an
ArrayIndexOutOfBoundsException.
An array of length 6 has slots 0, 1, 2, 3, 4 and 5. There is no slot 6. The count and the last index are different numbers, and confusing them is the single most common array error there is.
| Expression on a length-6 array | Result |
|---|---|
tideHeights[0] | The first reading |
tideHeights[5] | The last reading |
tideHeights[tideHeights.length − 1] | The last reading, written without a hard-coded 5 |
tideHeights[6] | ArrayIndexOutOfBoundsException |
tideHeights[tideHeights.length] | ArrayIndexOutOfBoundsException — the same mistake, dressed up |
tideHeights[−1] | ArrayIndexOutOfBoundsException — below the range counts too |
tideHeights[6] compiles. Nothing is wrong
with it as a piece of Java; it is only wrong about this particular object, and that is not known
until the line runs. A question asking “what does this code do?” wants
throws ArrayIndexOutOfBoundsException,
not “will not compile.”
5length Is an Attribute, Not a Method
tideHeights.length // correct — an array
tideHeights.length() // does not compile
berth.length() // correct — a String
list.size() // correct — an ArrayList
Array → .length with no brackets. String →
.length() with brackets. ArrayList →
.size(). There is no logic to learn here; it is memorized, and it is
marked.
6Arrays of Object References
The second half of 4.3.A.1 is the part that gets skipped: the values in an array can be object references. Nothing about the array changes — there are still fixed, numbered slots — but what a slot holds is an arrow to an object somewhere else.
Buoy[] markers = new Buoy[3]; // three slots, all null
markers[0] = new Buoy("Pillar Rock", 4);
markers[1] = new Buoy("Cutter Shoal", 2);
After those three lines the array holds two references and one
null. That gives two different ways to change what
slot 0 means, and they are not the same operation:
| Statement | What changes |
|---|---|
markers[0].setFlashes(6); | The object is modified. The slot still holds the same reference. |
markers[0] = new Buoy("Pillar Rock", 6); | The slot is modified. A different object is now referenced; the first one is untouched. |
The distinction is the whole content of essential knowledge 4.4.A.5 in enhanced for loops: the loop variable is a copy of the reference, so calling a method on it changes the object, and assigning to it changes nothing that survives the iteration.
7How This Is Assessed
Multiple-choice questions on 4.3.A are usually one of five shapes:
| Shape | What is really being tested |
|---|---|
| An initializer list, then “what is printed?” | Counting the braces and mapping index to position |
A new array, then a read before any write | The default values — 4.3.A.3 |
An index that is exactly length | The off-by-one, and knowing it throws at run time |
.length() written on an array | Attribute versus method |
| A method called on a slot of a new object array | null defaults — a NullPointerException |
Draw the slots and number them before answering. Six boxes labeled 0 to 5 turns every one of these into reading off a picture, and it takes about four seconds.
8Check Yourself
What does int[] counts = new int[3];
leave in the array?
Three slots, each holding 0. Not empty and
not undefined — creating with new fills
every slot with the default value for the element type.
An array is created with {9, 4, 7, 2}.
What is its length, and what is the largest valid index?
Length 4, largest valid index 3. The two numbers are always one apart, which is why
arr[arr.length − 1] is the safe way to
reach the last element.
Why does markers[2].setFlashes(3);
throw on a freshly created Buoy[3]?
Because the default for a reference type is null.
Creating the array creates the array and nothing else, so slot 2 references no object and the
method call is a NullPointerException.
Can an array created with length 5 later be made to hold 6 values?
No. The length is established at creation and cannot change. A six-slot array can be created and the five values copied into it, but that is a different object — the original is unchanged and simply stops being referenced.
Two of these three compile. Which does not, and why?
arr.length · word.length() ·
arr.length()
arr.length(). On an array, length is an
attribute, so it takes no brackets; on a String,
length() is a method, so it does.
9Summary
| Statement | What to remember |
|---|---|
| 4.3.A.1 | Same type in every slot; the values may be primitives or object references |
| 4.3.A.2 | Length is fixed at creation; read it with .length, no brackets |
| 4.3.A.3 | new fills every slot: 0, 0.0, false, null |
| 4.3.A.4 | An initializer list sets the length from the number of values listed |
| 4.3.A.5 | [] both reads and writes; an element acts like a variable |
| 4.3.A.6 | Valid indices are 0 to length − 1; anything else throws at run time |
| Object arrays | Creating the array creates no elements — every slot is null |
An array is a single object holding a fixed row of numbered, already-filled slots — which is why the length can never change, why nothing is ever empty, and why the last index is always one less than the count.