APrep Open the app

AP Computer Science A · Unit 4: Data Collections

4.1 ArrayCreation and Access

Declaring and Creating Arrays

An array is a fixed-size collection storing multiple values of the same type. Declare with `int[] nums;` then create with `new int[5]` to allocate 5 slots. You can also use an initializer list: `int[] nums = {1, 2, 3};`. Array size is set at creation and cannot change afterward.

Indexing and Length

Array elements are accessed using zero-based indexing: the first element is at index 0, the last at `length - 1`. Use `array.length` (no parentheses — it's a field, not a method) to get the number of elements. Accessing an invalid index throws an ArrayIndexOutOfBoundsException.

Traversing Arrays

Loops are commonly used to process every element. A standard `for` loop with index `i` from `0` to `array.length - 1` allows reading and modifying elements. An enhanced for loop (`for (int x : nums)`) simplifies reading values but cannot modify the original array's elements.

Key terms

Array
A fixed-size collection of elements of the same type, accessed by index.
Zero-based indexing
Array indexing starts at 0; the first element is index 0, the last is length-1.
array.length
A field (not a method) that returns the number of elements in an array.
ArrayIndexOutOfBoundsException
Thrown when accessing an index less than 0 or greater than/equal to array length.
Enhanced for loop limitation
It can read array elements but cannot modify the original array's values.

Try an AP-style question

Code

int[] a = new int[5];
System.out.print(a[2]);

What is printed?

  1. An error
  2. 0
  3. 2
  4. null
Show the answer

B. Default int value.

Practice 8 AP-style questions with instant explanations, flashcards and spaced review.

Study 4.1 free in APrep