TOPIC 4.3 · STUDY

Array Creation and Access

An array is a fixed-length sequence of slots of one type. new int[n] makes n slots filled with 0; an initializer list sets both values and length. Indexes run from 0 through length - 1, and length is a field, not a method.

4.3.A

Array creation and access

An array holds several values of the same type in numbered slots. Creating int[] trays = new int[6]; builds six int slots. The expression trays.length is 6. That length is fixed when the array is created; you do not grow or shrink it later.

int[] trays = new int[6];
System.out.println(trays.length);

length is a field on the array, written trays.length with no parentheses. Do not write trays.length(). That form is for String, not for arrays.

Six equal slots indexed 0 through 5, each storing 0, with length marked as 6.

new int[6] makes six slots. Each starts at 0. Valid indexes are 0 through 5; length is 6.

Indexes start at 0 and run through length - 1. For six slots, the last valid index is 5. Reading or writing trays[0] through trays[5] is allowed. Using an index outside that range throws ArrayIndexOutOfBoundsException.

trays[0] = 4;
trays[5] = trays[0] + 1;
System.out.println(trays[5]);

The [] operator both reads and writes. After those lines, index 5 holds 5. Unassigned int slots keep the default 0. new int[n] fills every slot with 0; new double[n] fills with 0.0; new boolean[n] fills with false.

Reference arrays are different. new String[3] still has length 3, but each slot starts as null until you assign an object. The array itself is not null; only the unused reference slots are.

String[] tags = new String[3];
tags[2] = "dock";
System.out.println(tags[0] + " " + tags[2]);

That print shows null dock because index 0 was never assigned. An initializer list sets both the stored values and the length in one step.

int[] lanes = {7, 2, 9};
System.out.println(lanes.length);
System.out.println(lanes[lanes.length - 1]);

lanes has length 3. The last element is lanes[lanes.length - 1], which is lanes[2] and holds 9. Writing lanes[3] or lanes[-1] is out of bounds and throws ArrayIndexOutOfBoundsException. This topic covers creating arrays and reading or writing single indexes. Walking every slot with a loop comes later.

Key points

  • new int[n] creates n slots; length equals n and stays fixed.
  • length is a field (arr.length), not a method (arr.length()).
  • Valid indexes run from 0 through length - 1.
  • new int[n] defaults every slot to 0; reference arrays default slots to null.
  • An initializer list sets the values and the length together.
  • An index outside 0..length-1 throws ArrayIndexOutOfBoundsException.

length is the number of slots, not the last index. For length 6 the last valid index is 5. arr[arr.length] is always out of bounds.

Practice this topic