College Board Unit 4
How it works
Changing an array means assigning into an indexed position, as in arr[i] = value. The enhanced for loop cannot do this, because its variable is a copy of the element rather than the storage location itself. Arrays are reference types, so passing one to a method or assigning it to another variable shares the same underlying storage: changes made through either name are visible through both.
Trace array contents after each assignment, and note when two names alias one array.
Common error
Assuming a method received a copy. It received a reference, and its changes persist.
Worked example
Java
int[] values = {3, 6, 9};
for (int i = 0; i < values.length; i++) values[i]++;
System.out.println(Arrays.toString(values));Output
[4, 7, 10]The indexed assignment updates the underlying array rather than a local copy of an element.
Exercises
5.3.1 · Trace
Determine the exact output. Explain the Java rule or state changes that produce it.
Java
int[] a = {1, 2, 3, 4};
for (int i = 1; i < a.length; i++) a[i] = a[i - 1];
System.out.println(Arrays.toString(a));Show solution
Output
[1, 1, 1, 1]Each iteration reads the value that the preceding iteration already overwrote.
5.3.2 · Write code
Write public static void reverse(int[] values). Reverse the array in place using swaps. Empty and one-element arrays should remain valid.
Show solution
One valid solution is shown below. Other implementations satisfying the contract are also valid.
Java
public static void reverse(int[] values) {
for (int i = 0; i < values.length / 2; i++) {
int opposite = values.length - 1 - i;
int temp = values[i];
values[i] = values[opposite];
values[opposite] = temp;
}
}Check your code
Java
int[] a = {1,2,3,4}; reverse(a); System.out.println(Arrays.toString(a));
int[] b = {}; reverse(b); System.out.println(Arrays.toString(b));
int[] c = {8}; reverse(c); System.out.println(Arrays.toString(c));Expected output
[4, 3, 2, 1]
[]
[8]