College Board Unit 4
How it works
An array holds a fixed number of elements of one type, created either with new int[n] or with an initializer list. Arrays created with new start at default values: 0 for int, 0.0 for double, false for boolean, and null for object types. The size is available through the length field, written without parentheses, and valid indexes run from 0 through length - 1.
State the length and the valid index range before writing any loop over it.
Common error
Confusing length, which is a field on arrays, with length(), which is a method on Strings.
Worked example
Java
int[] scores = new int[3];
scores[1] = 8;
System.out.println(scores.length);
System.out.println(scores[0] + scores[1]);Output
3
8There are three elements. The unassigned element at index 0 retains its default value.
Exercises
5.1.1 · Trace
Determine the exact output. Explain the Java rule or state changes that produce it.
Java
int[] a = {4, 6, 8};
int[] b = a;
b[0] = 9;
System.out.println(a[0]);Show solution
Output
9Both references point to the same mutable array, so either reference can observe the mutation.
5.1.2 · Write code
Create an int array of length four. Set its first element to 7 and its last to 12, then print all four values in index order using Arrays.toString.
Show solution
One valid solution is shown below. Other implementations satisfying the contract are also valid.
Java
int[] values = new int[4];
values[0] = 7;
values[values.length - 1] = 12;
System.out.println(Arrays.toString(values));