Topic 4.1 — Array Creation and Access

Goal: create arrays, understand zero-based indexing, use length, and access/modify elements safely.

The big idea

An array is a fixed-size collection of items of the same type. Each item lives in a numbered slot called an index.

On AP CSA, you must be comfortable reading array code and predicting values at specific indexes.

Array facts (memorize)

  • Indexes start at 0.
  • Last index is length - 1.
  • Arrays have a length field (no parentheses): arr.length
  • Size is fixed after creation.

Create an array (two main ways)

Way Code What it means
Specify size int[] scores = new int[5]; Creates 5 int slots (default values at first).
Initializer list int[] scores = {10, 20, 30}; Creates an array with those values (size becomes 3).
int[] a = new int[4];     // size 4, indexes 0..3
int[] b = {2, 4, 6, 8};   // size 4, already filled

Default values (when you use new type[size])

If you don’t fill an array yet, Java gives each slot a default value:

Type Default value
int0
double0.0
booleanfalse
reference types (like String)null

Index errors (very testable)

  • Valid indexes are 0 through arr.length - 1.
  • Using an invalid index causes an ArrayIndexOutOfBoundsException.
int[] nums = {5, 7, 9};  // length = 3
System.out.println(nums[3]);  // ❌ invalid (last index is 2)

Access and update elements

Use brackets [ ] to access or change a specific element.

int[] nums = {10, 20, 30};

int first = nums[0];   // access
nums[1] = 99;          // update

// nums is now {10, 99, 30}

Index picture

Index 0 1 2
Value 10 99 30

The index tells you the position; the value is what’s stored there.

Using length

Arrays use length (field), not length() (method).

int[] nums = {4, 8, 12, 16};
int n = nums.length;        // 4
int last = nums[nums.length - 1];  // 16

Common mistakes

  • Using length() instead of length for arrays.
  • Forgetting arrays start at index 0.
  • Assuming the size can change after creation.
  • Trying to access arr[arr.length] (off by one).
// Off-by-one bug:
int[] a = new int[5];
a[a.length] = 1; // ❌ last valid index is a.length - 1

Quick self-check

  1. If an array has length 10, what are the first and last valid indexes?
  2. What does new int[3] contain before you assign values?
  3. What’s the value of a.length if int[] a = {2, 5, 8};?
  4. Fix the bug: arr[arr.length] = 0;
  5. Predict: after nums[0] = nums[2];, what changes?

← Back to Unit 4 topics