Unit 4 Cycle 1 Day 2: Array Initializer List
Share
Array Initializer List
Section 4.1 — Array Creation and Access
Key Concept
An array initializer list creates and populates an array in one statement: int[] arr = {3, 7, 2, 9}. The array's length is determined by the number of values provided. This syntax can only be used in the declaration statement, not in a later assignment. To assign a new array later, use arr = new int[]{3, 7, 2, 9}. The AP exam tests initializer lists with different data types and asks about the resulting array length and element values.
Consider the following code segment.
What is printed?
Answer: (B) 25
vals.length is 5. vals[5-1] = vals[4] = 25. The last element of an array is always at index length - 1.
Why Not the Others?
(A) 5 is at index 0 (first element), not the last.
(C) 20 is at index 3, one before the last.
(D) Index 4 is valid for an array of length 5 (indices 0-4).
Common Mistake
Arrays are zero-indexed. The last valid index is length - 1. Using length as an index causes ArrayIndexOutOfBoundsException.
AP Exam Tip
arr[arr.length - 1] always gives the last element. arr[arr.length] always causes an error. This distinction is critical.