2.2.9 Declaring and Instantiating Arrays

Overview

An array variable holds a reference to an array object. Declaring the variable names the type, while `new` creates storage for a chosen number of elements. In a one-dimensional `int[]`, the length is fixed when the instance is created.

int[] seatNumbers;
seatNumbers = new int[3];
Create the Array Instance
Object diagram for declaring and instantiating arrays: create the array instance.
Create the Array Instance
  • New
  • Changed
  • Removed

The first line declares an array reference. The second creates an array of three integers and stores its reference in seatNumbers. Its elements initially contain the default int value 0. A declaration by itself does not provide elements to index.

An array length cannot be changed after creation. To use a different number of positions, create another array instance and assign its reference. Later code can replace values in the existing positions.

Trace the Outcome

Identify the valid indexes immediately after `new int[3]`. Explain what would be missing if only the first line had executed.