AP Computer Science A · Unit 4 lecture · Part 2 of 14 · 8 min

4.3 Array creation and accessArrays: many values, one name

Mr. Thompkins
Ten quiz scores. Do you want ten variables, score1 through score10, and ten nearly identical lines of code for each job? Neither do I. An array gives them one name and a number each.

An array holds a fixed number of values, all of the same type, under one name. Each value is an element, and each element has an index: its position, starting at 0. An array of length 4 has indexes 0, 1, 2 and 3, so the last index is always length - 1. Once an array is created, its length never changes.

?Wait, why do indexes start at 0?
Same as Strings in Unit 1: in "cat", the c is at index 0, so substring(0, 1) is "c". Think of the index as how many steps you take from the start. The first element is zero steps in.

There are two ways to make an array. new int[4] makes an array with 4 elements that all start at a default value. An initializer list, like {2.5, 4.0, 1.25}, makes an array that holds exactly those values, and Java counts them to get the length. Either way, you read or change one element with square brackets: laps[3] = 67;.

1int[] laps = new int[4];12double[] prices = {2.5, 4.0, 1.25};23String[] crew = new String[3];34boolean[] seen = new boolean[2];35laps[0] = 62;46laps[3] = laps[0] + 5;47System.out.println(laps[3] + " " + laps[1]);8System.out.println(prices.length + " " + prices[2]);59System.out.println(crew[0] + " " + seen[1]);
  1. line 1 new with a size: 4 ints, every one starts at 0
  2. line 2 Initializer list: the size comes from the values
  3. line 3-4 Object arrays start full of null; boolean arrays full of false
  4. line 5-6 Square brackets read or change one element
  5. line 8 length is a field: no parentheses
output › 67 0 3 1.25 null false
Making arrays, writing elements and reading them back.
laps6200102673laps.length is 4valid indexes: 0 to 3laps[4] throws an exceptionblue: assigned; white: still the default 0
The laps array after the code runs.

The defaults are the same ones instance variables get: 0 for int, 0.0 for double, false for boolean and null for any object type. So new String[3] makes three empty slots, not three Strings. Each slot holds null until you store a String in it.

?Wait, is it length or length()?
For an array, length is a field: prices.length, no parentheses. For a String, length() is a method, with parentheses. Mixing them up is a compile error, and the exam knows you might.

The index must be from 0 to length - 1. Any other index compiles fine but crashes when it runs, with an ArrayIndexOutOfBoundsException. The most common way to get there is asking for t[t.length].

1int[] t = {4, 8, 15};2System.out.println(t[t.length]);1
  1. line 2 t.length is 3, but the last index is 2
output › Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
A run-time error, not a compile error. This is the real message.

One more fact matters a lot later. An array is an object, so an array variable holds a reference to it, just like the object variables in Unit 3. int[] b = a; doesn't copy the array. It makes b a second name for the same array.

ab902132int[] b = a; copies the arrowone array, two namesb[0] = 9 changes a[0] too
Two variables, one array. A change through either name is a change to the one array.
Pause and think
After int[] a = {1, 2, 3}; int[] b = a; b[0] = 9; what is a[0]? And how would you make b a separate copy?
I thought about it. Show me
a[0] is 9, because a and b refer to the same array. For an independent copy, make a new array of the same length, int[] b = new int[a.length];, then copy each element with a loop: b[i] = a[i];.
Trace the array

What does this print?

int[] q = new int[6];
q[2] = 5;
q[q[2]] = q[2] * 2;
q[q.length - 2] = 1;
System.out.println(q[5] + " " + q[4] + " " + q[0]);
  1. new int[6] makes six 0s, indexes 0 to 5. Then q[2] = 5.
  2. q[q[2]]: work from the inside out. q[2] is 5, so this is q[5] = 5 * 2 = 10.
    Why?
    An index can be any int expression, including another element.
  3. q.length - 2 is 4, so q[4] = 1.
  4. q[0] was never assigned, so it's still 0. The output is 10 1 0.

Answer: 10 1 0

Stuck? Get a hint
  1. Write six boxes numbered 0 to 5, all holding 0.
  2. For q[q[2]], first find q[2], then use that value as the index.
  3. q.length is 6.
Check yourself
What is printed?
int[] a = new int[5];
a[1] = 4;
a[a[1]] = 9;
System.out.println(a[4] + a[0] + " " + a.length);
  1. A9 5
  2. B90 5
  3. C9 4
  4. DNothing: an ArrayIndexOutOfBoundsException is thrown
Show the answer

A. a[1] is 4, so a[a[1]] = 9 stores 9 at index 4, which is the last valid index of a length-5 array. Then a[4] + a[0] is 9 + 0, added as ints before the String joins in, so "9 5". The second choice is the trap: + adds the two ints first because it works left to right.

  • new type[n] makes n elements with defaults (0, 0.0, false, null). An initializer list sets the values and the length.
  • Indexes run from 0 to length - 1. length is a field: no parentheses.
  • An index outside that range throws ArrayIndexOutOfBoundsException when the code runs.
  • Array variables hold references. Assigning one to another makes an alias, not a copy.