2.2.9 Initializing Arrays With Values

Create a Soccer Array with Known Scores

When the scores are already known, an array initializer can create the array and supply its element values together. This avoids creating zero-filled positions and assigning each score separately.

Plan the Stored Order
Worked soccer example
Listed value Assigned index Round represented
2 0 Round 1
0 1 Round 2
3 2 Round 3
Explore the Soccer Example

Place this local definition inside an existing method. The three values represent training rounds 1, 2, and 3 in order.

Create a Soccer Array with Known Scores
int[] roundGoals = { 2, 0, 3 };
Understand the Code

Read the values from left to right

The braces contain the values to store. The first value, 2, goes into index 0. The next value, 0, goes into index 1. The final value, 3, goes into index 2.

Commas separate values; the square brackets in int[] still identify the variable type.

Let the initializer determine the count

There are three listed values, so the created array has three elements. Appending a fourth listed score would create a four-element array instead.

Unlike a bare definition, this initialized definition creates an instance and assigns its reference to the local.

Each value must fit the element type

The element type is int. All listed scores must be compatible with that type. A text description such as Two goals is not an int score.

A zero score is still an element

The middle zero occupies a real position. It records a round with no goals in this model. It does not remove that round from the sequence or shift the next score into its place.

Preserve the connection between order and rounds

Suppose the coach reports 2 goals, then 0, then 3. The initializer must preserve that order if each position represents the next training round. Rearranging the values would preserve the total but misrepresent individual rounds.

Check both the number of values and their order. An initializer is useful here because all three scores are known when this statement executes; it does not mean later scores can never be corrected.

Try a Small Change
Predict the Result
Confirm the Final Array Snapshot

This snapshot confirms the original three-score initializer. The two-score practice variation has a different array shape.

Create a Soccer Array with Known Scores.
Create a Soccer Array with Known Scores
  • New
  • Changed
  • Removed

The diagram matches the completed initializer. The middle position still exists even though its score is zero. The values remain in the same left-to-right order as the definition.