Lesson 4.3: Array Creation and Access

Unit 4 · Lesson 4.3 · Arrays

Lesson 4.3: Array Creation and Access

🕑 35–45 min · 10 Practice Questions · New Syntax · Coding Exercises

What You'll Learn

  • 4.3.A: Represent a list of data using an array.
  • 4.3.B: Access and update individual elements of an array.
  • Declare and initialize arrays using both new and initializer list syntax.
  • Explain 0-based indexing and use array.length correctly.
  • Identify when and why ArrayIndexOutOfBoundsException occurs.
  • Describe what default values Java assigns to uninitialized array elements.

Key Vocabulary

Term Definition
array A fixed-size, ordered collection of elements of the same type stored in contiguous memory locations.
index The integer position of an element in an array. Arrays are 0-indexed: the first element is at index 0, the last at index length - 1.
array.length A public final field (not a method) that stores the number of elements in the array. Note: no parentheses.
default value The value Java automatically assigns to each element when an array is created with new: 0 for numeric types, false for boolean, null for objects.
ArrayIndexOutOfBoundsException A runtime exception thrown when code tries to access an index that is negative or greater than or equal to array.length.
initializer list A shorthand to declare and populate an array in one statement using curly braces: int[] scores = {92, 74, 88};

Declaring and Creating Arrays (4.3.A)

In Lesson 4.2 you learned that a collection holds many objects together. The array is Java's simplest collection — a fixed-size, ordered list where every element is the same type.

Syntax: Two Ways to Create an Array

Method 1 — Using new: Creates an array of a given size. All elements start at their default value.

int[] scores = new int[5];       // 5 integers, all initialized to 0
String[] names = new String[3];  // 3 Strings, all initialized to null
boolean[] flags = new boolean[4];// 4 booleans, all initialized to false

Method 2 — Initializer list: Declares the array and fills it with specific values in one line. Java infers the size automatically.

int[] scores = {92, 74, 88, 58};          // size 4, values set immediately
String[] days = {"Mon", "Tue", "Wed"};    // size 3
double[] prices = {1.99, 4.50, 12.00};   // size 3

📌 Fixed Size — This Matters

Once an array is created, its size cannot change. new int[5] always has exactly 5 slots. If you need a collection that grows or shrinks, you'll use ArrayList (Lesson 4.7). For now: arrays are the right choice when the size is known in advance.

What the Array Looks Like in Memory

Picture a row of labeled boxes. Each box holds one value. Each box has a number (its index) starting at 0:

92 74 88 58
[0] [1] [2] [3]

This is int[] scores = {92, 74, 88, 58}; — 4 elements, indices 0 through 3, length is 4.

Accessing and Updating Elements (4.3.B)

Reading a Value

Use bracket notation with the index to read a specific element:

int[] scores = {92, 74, 88, 58};

System.out.println(scores[0]);  // prints 92
System.out.println(scores[2]);  // prints 88
System.out.println(scores[3]);  // prints 58 (last element)

Writing (Updating) a Value

Use the same bracket notation on the left side of an assignment to change an element:

scores[1] = 80;   // replaces 74 with 80
scores[3] = 95;   // replaces 58 with 95
// array is now {92, 80, 88, 95}

Using array.length

length is a field (not a method — no parentheses) that gives the number of elements:

int[] scores = {92, 74, 88, 58};
System.out.println(scores.length);       // prints 4
System.out.println(scores[scores.length - 1]);  // prints 58 (last element)

⚠️ AP Exam Trap: length vs. last index

For an array of size n, valid indices are 0 through n−1. The last index is always array.length - 1, never array.length. This is the most common source of ArrayIndexOutOfBoundsException on the AP exam.

Default Values

When you create an array with new without an initializer list, Java fills every slot automatically:

Type Default Value Example
int, double, long 0 / 0.0 new int[3] → {0, 0, 0}
boolean false new boolean[2] → {false, false}
String / Object null new String[3] → {null, null, null}

⚠️ AP Exam Trap: Calling methods on null

If you create String[] names = new String[3] and then call names[0].length() without first assigning a value, you get a NullPointerException at runtime. Always assign values before calling methods on object array elements.

Array Bounds and ArrayIndexOutOfBoundsException

Java checks every array access at runtime. If your index is negative or ≥ array.length, you get an ArrayIndexOutOfBoundsException:

int[] scores = {92, 74, 88, 58};  // valid indices: 0, 1, 2, 3

scores[-1]           // EXCEPTION: negative index
scores[4]            // EXCEPTION: index 4 doesn't exist (length is 4)
scores[scores.length] // EXCEPTION: same problem — length is 4, last valid is 3

✅ Example: Safe Last-Element Access

int[] scores = {92, 74, 88, 58};
int last = scores[scores.length - 1];  // 4 - 1 = 3 → scores[3] = 58 ✓

This pattern — array[array.length - 1] — is the standard way to access the last element. Memorize it.

Arrays of Objects

Arrays aren't limited to primitives. You can store objects — including instances of classes you write in Unit 3:

// Assume Student class exists from Unit 3
Student[] roster = new Student[3];
roster[0] = new Student("Alice", 92);
roster[1] = new Student("Ben",   74);
roster[2] = new Student("Carlos", 58);

System.out.println(roster[0].getName());  // prints "Alice"

This is exactly the row-to-object mapping from Lesson 4.2 — now in actual Java syntax. Each array slot holds one object, which represents one record in the data set.

Summary

  • Arrays hold a fixed number of elements, all the same type. Size cannot change after creation.
  • Two creation styles: new int[n] (default values) and {v1, v2, v3} (initializer list).
  • Arrays are 0-indexed. First element is arr[0], last is arr[arr.length - 1].
  • array.length is a field, not a method — no parentheses.
  • Default values: 0 for numbers, false for boolean, null for objects.
  • Accessing an invalid index throws ArrayIndexOutOfBoundsException at runtime.

Practice Questions

MCQ 1
What is the value of nums[2] after executing int[] nums = {10, 20, 30, 40, 50};?
Predict before reading the options.
A 20
B 40
C 30
D 50
C. Index 0 = 10, index 1 = 20, index 2 = 30. Counting from zero is the single most important habit to build with arrays.
MCQ 2
Given int[] data = new int[6];, what is the value of data[3] before any assignments are made?
Predict before reading the options.
A An unpredictable garbage value
B 0
C null
D 6
B. Java initializes all int array elements to 0 by default. A is wrong — Java guarantees default values (unlike C/C++). C would be correct for a reference type array. D (the size) has no relation to element values.
MCQ 3
Which expression correctly accesses the last element of an array named vals?
Predict before reading the options.
A vals[vals.length]
B vals[vals.length()]
C vals[vals.length + 1]
D vals[vals.length - 1]
D. A throws ArrayIndexOutOfBoundsException because length is one past the last index. B won't compile — length is a field, not a method, so no parentheses. C is also out of bounds. D is correct: last index = length - 1.
MCQ 4
Which line causes an ArrayIndexOutOfBoundsException?
A
int[] arr = {5, 10, 15};
System.out.println(arr[3]);
B
int[] arr = {5, 10, 15};
System.out.println(arr[0]);
C
int[] arr = {5, 10, 15};
System.out.println(arr[arr.length - 1]);
D
int[] arr = {5, 10, 15};
System.out.println(arr[2]);
A. The array has 3 elements at indices 0, 1, 2. Index 3 doesn't exist — it throws ArrayIndexOutOfBoundsException. B accesses index 0 (valid). C accesses arr[2] = 15 (valid). D accesses index 2 directly (valid).
MCQ 5
What does the following code print?
int[] arr = {3, 6, 9, 12};
arr[1] = arr[3];
System.out.println(arr[1]);
Predict the output before reading the options.
A 3
B 6
C 12
D 9
C. arr[3] is 12. arr[1] = arr[3] copies the value 12 into slot 1. So arr[1] is now 12. The original value 6 is overwritten.
MCQ 6
How many elements does the following array contain? String[] items = {"apple", "banana", "cherry", "date"};
A 3
B 4
C 5
D Cannot be determined without calling items.length()
B. There are 4 string literals in the initializer list, so the array has 4 elements. D is wrong on two counts: you can count the values, and length is a field not a method — no parentheses.
Tier 3 · AP Mastery

Mastery: Array Creation and Access

MCQ 7
What is printed by the following code?
int[] nums = new int[4];
nums[0] = 5;
nums[2] = nums[0] * 2;
System.out.println(nums[1] + nums[2] + nums[3]);
Trace through carefully before selecting.
A 15
B 5
C 20
D 10
D. After initialization: all slots are 0. After assignments: nums[0]=5, nums[2]=10. nums[1] and nums[3] were never assigned, so they remain 0. Sum = 0 + 10 + 0 = 10. The trap is forgetting that unassigned slots default to 0.
MCQ 8
Which of the following correctly swaps the first and last elements of array arr?
Predict the answer before reading the options.
A
int temp = arr[0];
arr[0] = arr[arr.length - 1];
arr[arr.length - 1] = temp;
B
arr[0] = arr[arr.length - 1];
arr[arr.length - 1] = arr[0];
C
arr[0] = arr[1];
arr[arr.length - 1] = arr[0];
D
int temp = arr[arr.length];
arr[0] = arr[arr.length - 1];
arr[arr.length] = temp;
A. A is the classic swap using a temp variable — the only correct approach. B overwrites arr[0] first, so both slots end up with the same value (no swap). C swaps the wrong indices. D uses arr[arr.length], which is out of bounds.
MCQ 9
A Student class has a constructor Student(String name, int score) and a method getScore(). After executing:
Student[] roster = new Student[3];
roster[0] = new Student("Alice", 92);
roster[2] = new Student("Carlos", 74);
What happens when roster[1].getScore() is called?
Predict before reading the options.
A Returns 0
B Throws a NullPointerException
C Throws ArrayIndexOutOfBoundsException
D Returns null
B. roster[1] was never assigned — it holds the default value null for a reference type. Calling .getScore() on null throws a NullPointerException. A would be the default int value, but you can't even reach getScore() to return it. C is wrong — index 1 is valid (0, 1, 2 are all in range).
MCQ 10
What is the output of the following code?
int[] x = {2, 4, 6, 8, 10};
x[0] = x[0] + x[4];
x[4] = x[0] - x[4];
x[0] = x[0] - x[4];
System.out.println(x[0] + " " + x[4]);
Trace every step before selecting — this is an AP-style tricky trace.
A 2 10
B 12 2
C 10 2
D 2 12
C. This is the XOR-free arithmetic swap. Trace it step by step:
Start: x[0]=2, x[4]=10
Step 1: x[0] = 2 + 10 = 12
Step 2: x[4] = 12 - 10 = 2
Step 3: x[0] = 12 - 2 = 10
Result: x[0]=10, x[4]=2. This is a classic swap-without-temp pattern — the AP exam loves testing whether students trace mutations carefully.

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]