Lesson 4.3: Array Creation and Access
Lesson 4.3: Array Creation and Access
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
newand initializer list syntax. - Explain 0-based indexing and use
array.lengthcorrectly. - Identify when and why
ArrayIndexOutOfBoundsExceptionoccurs. - 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 isarr[arr.length - 1]. -
array.lengthis a field, not a method — no parentheses. - Default values:
0for numbers,falsefor boolean,nullfor objects. - Accessing an invalid index throws
ArrayIndexOutOfBoundsExceptionat runtime.
Practice Questions
nums[2] after executing int[] nums = {10, 20, 30, 40, 50};?int[] data = new int[6];, what is the value of data[3] before any assignments are made?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.vals?vals[vals.length]
vals[vals.length()]
vals[vals.length + 1]
vals[vals.length - 1]
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.ArrayIndexOutOfBoundsException?int[] arr = {5, 10, 15};
System.out.println(arr[3]);
int[] arr = {5, 10, 15};
System.out.println(arr[0]);
int[] arr = {5, 10, 15};
System.out.println(arr[arr.length - 1]);
int[] arr = {5, 10, 15};
System.out.println(arr[2]);
ArrayIndexOutOfBoundsException. B accesses index 0 (valid). C accesses arr[2] = 15 (valid). D accesses index 2 directly (valid).int[] arr = {3, 6, 9, 12};
arr[1] = arr[3];
System.out.println(arr[1]);
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.String[] items = {"apple", "banana", "cherry", "date"};
items.length()
length is a field not a method — no parentheses.Mastery: Array Creation and Access
int[] nums = new int[4]; nums[0] = 5; nums[2] = nums[0] * 2; System.out.println(nums[1] + nums[2] + nums[3]);
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.arr?int temp = arr[0]; arr[0] = arr[arr.length - 1]; arr[arr.length - 1] = temp;
arr[0] = arr[arr.length - 1]; arr[arr.length - 1] = arr[0];
arr[0] = arr[1]; arr[arr.length - 1] = arr[0];
int temp = arr[arr.length]; arr[0] = arr[arr.length - 1]; arr[arr.length] = temp;
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.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?NullPointerException
ArrayIndexOutOfBoundsException
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).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]);
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.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]