Arrays

AP Computer Science A · Unit 4: Data structures

Arrays notes

Fact-checked by a second, independent AI review.

Core ideas: arrays are fixed-size, zero-based collections; you access elements by index and use length to bound loops. Typical questions test indexing, looping, and basic operations like search or copying.

Array basics
An array stores elements of a single type; its size is fixed and accessed via length.
Zero-based indexing
First element is at index 0; last element is at index length-1.
Traversal and loops
Use a for loop with i from 0 to length-1; enhanced for (for-each) works for read-only element access.
Common operations
Copying arrays, searching (linear search), and using Arrays methods like copyOf; remember fixed size.
Common pitfalls
Off-by-one errors and ArrayIndexOutOfBoundsException; ensure loop bounds match length and handle empty arrays.

Remember it: Mnemonic: '0 to L-1' = your index range; always think in terms of 0-based bounds.

Exam tip: Markers check correct use of length, proper bounds in loops, and avoidance of out-of-bounds errors; prefer for loops with i < arr.length and use enhanced for when you don’t need indices.

Syllabus checklist

  • Arrays: core ideas
  • Terms and typical exam questions for "Data structures" in AP Computer Science A (Java
  • College Board)

Practice questions

  1. 1. Which expression returns the last element of an array arr?

    Answer checked

    Show answer

    Answer: arr[arr.length-1]. The last element is at index length-1, so arr[arr.length-1] is the correct expression.

  2. 2. True or False: In Java, arrays are objects.

    Answer checked

    Show answer

    Answer: True. Arrays in Java are reference types and are objects.

  3. 3. To loop over an array with an index, which condition stops before the first invalid index?

    Answer checked

    Show answer

    Answer: i < arr.length. i < arr.length ensures i stays within 0..length-1.

  4. 4. Given int[] a = {2, 5, 7, 3}; what is a[2]?

    Answer checked

    Show answer

    Answer: 7. Array indices start at 0; a[2] is the third element, 7.

  5. 5. What is the length of int[] a = new int[10];

    Answer checked

    Show answer

    Answer: 10. new int[10] creates an array with length 10.

Practise arrays as a game

Hearts, combos, streaks and an AI tutor that explains every answer. Start free.

Start free

More from Unit 4: Data structures