To use an array, the program needs both a variable that can refer to it and an array instance to store elements. Creating the array allocates a fixed number of element positions.
This local array will hold three int scores. The definition and creation are on separate lines so their jobs are visible.
int[] roundGoals;
roundGoals = new int[3];Define the reference first
int[] roundGoals; defines a local of array type. At this point, the local has not been assigned. It cannot yet supply an array for element operations.
Create and assign the instance
new int[3] creates an array with three int elements. The assignment stores its reference in roundGoals.
The 3 inside the creation brackets is the number of elements to allocate. It is not a request to access index 3.
Know the starting element values
All three int elements initially contain 0. These are usable initial values supplied when the array is created; they are not three scores the coach has entered.
A zero-initialized score cannot by itself tell whether a round has been played.
Keep the size and reference separate
The created array has three positions for its lifetime. Assigning a different array reference later would redirect the variable to another instance; it would not resize this particular array.
The two statements can also be written together as int[] roundGoals = new int[3];.
Read the number in the creation expression carefully
In new int[3], the 3 is the requested element count. It is not a stored score and it is not a valid position to access afterward. Three allocated elements have positions 0, 1, and 2.
Creation also gives those int positions their initial zero values. The local reference and the values inside its array therefore play different roles: the local lets code reach the array, while each element stores one score.
| Moment | What roundGoals can reach |
Elements |
|---|---|---|
| After definition | No assigned local reference yet | No array created |
| After creation and assignment | A three-element int array | 0, 0, 0 |
The picture shows the state after the second statement. There are three allocated positions and each contains zero. It does not depict the unassigned local immediately after definition.