ACSA Exam Prep
Unit 4 · Data Collections · Topic 4.3

Array Creation and Access

Skill 2.BSkill 3.B

Big idea: An array is a fixed-size row of numbered slots, all the same type. Index 0 is the first slot and length - 1 is the last.

Learning objectives
  • Develop code used to represent collections of related data using one-dimensional (1D) array objects.

Two ways to create an array

Code
int[] scores = new int[4];            // 4 slots, all 0
String[] names = {"Ana", "Bo", "Cy"};  // initializer list
scores[0] = 90;
scores[3] = 75;
System.out.println(scores[0] + " " + scores[1] + " " + scores[3]);
System.out.println(names.length + " " + names[2]);
Output
90 0 75
3 Cy

Default values

new fills every slot with a default: 0, 0.0, false, or null for references. An array of objects starts full of null; you have to create each object.

Code
double[] d = new double[2];
boolean[] b = new boolean[2];
String[] s = new String[2];
System.out.println(d[0] + " " + b[1] + " " + s[0]);
Output
0.0 false null

Bounds

Valid indexes are 0 to length - 1. Anything else throws an ArrayIndexOutOfBoundsException. The length can't change after creation.

Code
int[] a = {3, 6, 9};
System.out.println(a[a.length - 1]);
System.out.println(a[a.length]);
Output
9
throws ArrayIndexOutOfBoundsException

Arrays are objects

An array variable holds a reference. Assigning one array variable to another makes them aliases of the same array.

Code
int[] a = {1, 2, 3};
int[] b = a;
b[0] = 50;
System.out.println(a[0]);
Output
50
Key points
  • An array holds a fixed number of values of one type (primitives or references).
  • Length is fixed at creation and read with length (no parentheses).
  • new fills elements with defaults: 0, 0.0, false, or null.
  • An initializer list creates and fills an array at once.
  • Valid indexes: 0 to length - 1; otherwise ArrayIndexOutOfBoundsException.
Watch out
  • Arrays use .length, Strings use .length(), ArrayLists use .size().
  • new Dog[5] creates 5 null references, not 5 Dogs.
Quick check
int[] arr = new int[5]; What are arr.length and arr[4]?
Show answer
5 and 0.