2.2.14 Replacing Values in an Array

Replace One Recorded Soccer Score

An array element can appear on the left side of an assignment. This replaces the value at that position while keeping the other elements and the array length unchanged.

Explore the Soccer Example

The coach corrects the second round score from zero to one goal.

Replace One Recorded Soccer Score
int[] roundGoals = { 2, 0, 3 };
roundGoals[1] = 1;

int correctedScore = roundGoals[1];
Understand the Code

The left side chooses where to store

In roundGoals[1] = 1;, the index 1 selects the second position. The right-side int value 1 is stored there.

The two occurrences of 1 have different roles: one selects a position and the other is the replacement score.

Only the selected position changes

After the assignment, the sequence is 2, 1, 3. Index 0 still stores 2 and index 2 still stores 3. Length remains 3.

The operation does not insert a position or shift any existing score.

A later read sees the replacement

The final assignment reads index 1 again, so correctedScore receives 1. Reading the same element before the replacement would have produced 0.

An invalid target is still an error

Assigning through an index must obey the same bounds as reading. Using index 3 here would not append a score; it would attempt an out-of-range access.

Compare a stored copy with the corrected element

A local that received a score before a correction keeps its earlier int value. Replacing an array element updates that element; it does not locate and rewrite every local that previously read it.

Read the element again when you need its current score. This makes the timing of the read important when you compare a debugger local with the array after a correction.

Check the Values
Worked soccer example
Index Before replacement After replacement
0 2 2
1 0 1
2 3 3
Try a Small Change
Predict the Result
Use the Original Diagram to Check Your Reasoning

The diagram below shows the original example. Compare it with your prediction for the requested change; its pictured values have not been replaced by the practice inputs.

Replace One Recorded Soccer Score.
Replace One Recorded Soccer Score
  • New
  • Changed
  • Removed

The diagram shows the state after the replacement. Only the row at index 1 differs from the original initializer. There are still exactly three indexed rows.