AP Computer Science A Array — Worked Answer Explanations

Unit 6 · 12 questions explained

Below is a complete answer key for our AP Computer Science A Array practice questions. For each question you'll find the correct choice, a full written explanation of how to get there, and — for every wrong answer — a short note on exactly why it's tempting and where it goes wrong. Reading these straight through is one of the fastest ways to find the gaps in a unit before exam day.

Prefer to test yourself first? Take the timed Array practice test and come back here to review, or head back to the Array unit overview.

In-content ad
  1. Question 1 · Easy

    What is the output of the following code?

    int[] arr = {5, 10, 15, 20};
    System.out.println(arr.length);
    System.out.println(arr[2]);
    
    • A
      4\n15Correct
    • B
      4\n20
      Why not B: arr[2] is index 2, which is the third element (0-indexed): arr[0]=5, arr[1]=10, arr[2]=15.
    • C
      3\n15
      Why not C: arr.length is 4 (the number of elements). The last valid index is 3 (length - 1).
    • D
      4\n10
      Why not D: arr[2] is 15 (third element, 0-indexed). arr[1] = 10.
    Explanation

    arr.length returns the total number of elements (4). Arrays are 0-indexed, so arr[2] is the third element, which is 15.

    Key takeaway

    Arrays are 0-indexed: first element is at index 0, last is at index `length - 1`. `arr.length` gives the count.

  2. Question 2 · Easy

    What happens when the following code executes?

    int[] arr = new int[3];
    System.out.println(arr[0]);
    arr[5] = 10;
    
    • A
      0 is printed, then ArrayIndexOutOfBoundsException is thrown.Correct
    • B
      0 is printed, and arr[5] is set to 10.
      Why not B: The array has only 3 elements (indices 0, 1, 2). Accessing index 5 throws ArrayIndexOutOfBoundsException.
    • C
      NullPointerException is thrown on line 2.
      Why not C: new int[3] creates an array initialized to all zeros. It is not null. Accessing arr[0] returns 0 successfully.
    • D
      Compile error: arr[5] is out of bounds.
      Why not D: Array bounds are NOT checked at compile time in Java. The exception only occurs at runtime.
    Explanation

    new int[3] creates an array of 3 ints, all initialized to 0. arr[0] prints 0. arr[5] is beyond the valid range (0–2) and throws ArrayIndexOutOfBoundsException at runtime.

    Key takeaway

    Array bounds are checked at RUNTIME, not compile time. Accessing an invalid index throws ArrayIndexOutOfBoundsException.

  3. Question 3 · Easy

    What is the output of the following code?

    int[] nums = {3, 1, 4, 1, 5};
    int max = nums[0];
    for (int n : nums) {
        if (n > max) {
            max = n;
        }
    }
    System.out.println(max);
    
    • A
      3
      Why not A: 3 is only the starting value of max. The loop finds a larger value (5) and updates max.
    • B
      5Correct
    • C
      1
      Why not C: 1 is the smallest value in the array. The max algorithm tracks the largest.
    • D
      4
      Why not D: After seeing 4, max becomes 4. But then 5 is encountered and 5 > 4, so max updates to 5.
    Explanation

    The enhanced for loop iterates through all elements. max starts at 3. Comparing: 3 (no change), 1 (no), 4 (4>3→max=4), 1 (no), 5 (5>4→max=5). Final max = 5.

    Key takeaway

    The standard max pattern: initialize max to the first element, then iterate and update when a larger value is found.

  4. Question 4 · Easy

    What is the output of the following code?

    int[] arr = new int[5];
    for (int i = 0; i < arr.length; i++) {
        arr[i] = i * i;
    }
    System.out.println(arr[3]);
    
    • A
      6
      Why not A: arr[3] = 3*3 = 9, not 6.
    • B
      9Correct
    • C
      12
      Why not C: arr[3] = 33 = 9. 12 would be 34, which is not the formula used.
    • D
      16
      Why not D: arr[4] = 44 = 16. The question asks for arr[3] = 33 = 9.
    Explanation

    The loop sets arr[i] = i*i. So: arr[0]=0, arr[1]=1, arr[2]=4, arr[3]=9, arr[4]=16. arr[3] = 9.

    Key takeaway

    When filling arrays with formulas, trace the loop: each index `i` gets the value of the formula applied to `i`.

  5. Question 5 · Easy

    What is the output of the following code?

    int[] a = {1, 2, 3};
    int[] b = a;
    b[1] = 99;
    System.out.println(a[1]);
    
    • A
      2
      Why not A: b = a copies the reference, not the array. Both a and b point to the same array. Changing b[1] changes a[1].
    • B
      99Correct
    • C
      0
      Why not C: b = a makes b reference the same array. Modifying through b is visible through a.
    • D
      Compile error
      Why not D: Assigning one array reference to another is valid Java. Both variables then refer to the same underlying array.
    Explanation

    Arrays are objects in Java. b = a copies the reference (the memory address of the array), not the contents. Both a and b now point to the same array. b[1] = 99 modifies the shared array, so a[1] is also 99.

    Key takeaway

    Assigning an array variable copies the reference, not the data. Both variables see any changes made through either reference.

  6. Question 6 · Easy

    What is the value of result after the following code executes?

    int[] arr = {2, 5, 3, 8, 1};
    int result = 0;
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] % 2 == 0) {
            result++;
        }
    }
    
    • A
      1
      Why not A: Checking all elements: 2 (even), 5 (odd), 3 (odd), 8 (even), 1 (odd). Two elements are even: 2 and 8.
    • B
      2Correct
    • C
      3
      Why not C: Only 2 and 8 are even. 5, 3, and 1 are odd. Count = 2, not 3.
    • D
      5
      Why not D: result counts only even numbers, not all elements. 5 is the total length, not the count of even elements.
    Explanation

    The loop counts elements where arr[i] % 2 == 0 (even). Checking: 2 (even→result=1), 5 (odd), 3 (odd), 8 (even→result=2), 1 (odd). result = 2.

    Key takeaway

    The count pattern: initialize a counter to 0, increment when the condition is met during traversal.

  7. Question 7 · Easy

    What is the output of the following code?

    int[] arr = {10, 20, 30, 40, 50};
    for (int i = arr.length - 1; i >= 0; i--) {
        System.out.print(arr[i] + " ");
    }
    
    • A
      10 20 30 40 50
      Why not A: The loop iterates backwards (i starts at 4 and decrements). The output is reversed.
    • B
      50 40 30 20 10Correct
    • C
      40 30 20 10 0
      Why not C: arr.length - 1 is 4, so the loop starts at index 4 (value 50), not index 3 (value 40).
    • D
      ArrayIndexOutOfBoundsException
      Why not D: The loop correctly starts at index arr.length - 1 (=4) and ends at index 0 (i >= 0). All indices are valid.
    Explanation

    Backward traversal: i starts at arr.length - 1 = 4 and decrements to 0. So the indices accessed are 4, 3, 2, 1, 0 — values 50, 40, 30, 20, 10.

    Key takeaway

    Backward traversal: start at `arr.length - 1`, loop while `i >= 0`, decrement `i--`.

  8. Question 8 · Easy

    What is printed by the following code?

    int[] arr = {3, 7, 2, 9, 4};
    int sum = 0;
    for (int val : arr) {
        sum += val;
    }
    System.out.println(sum / arr.length);
    
    • A
      5Correct
    • B
      5.0
      Why not B: sum and arr.length are both ints. Integer division is used and the result is an int. The output is 5, not 5.0.
    • C
      25
      Why not C: 25 is the sum; dividing by arr.length (5) gives 25/5 = 5.
    • D
      4
      Why not D: Sum = 3+7+2+9+4 = 25. Average = 25/5 = 5 (integer division, but 25 is evenly divisible by 5).
    Explanation

    Sum = 3+7+2+9+4 = 25. arr.length = 5. Both are ints, so integer division: 25 / 5 = 5. Note: if the sum were not evenly divisible (e.g., sum=26), the result would truncate.

    Key takeaway

    Computing average with int variables uses integer division. Cast to double (`(double)sum / arr.length`) for a precise average.

  9. Question 9 · Easy

    What is the output of the following code?

    int[] arr = {5, 3, 8, 1, 9};
    int target = 8;
    int index = -1;
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == target) {
            index = i;
        }
    }
    System.out.println(index);
    
    • A
      2Correct
    • B
      8
      Why not B: The code stores the INDEX of the found element, not the element's value. Index 2 holds value 8.
    • C
      -1
      Why not C: -1 is the default (element not found). 8 IS in the array at index 2, so index is updated to 2.
    • D
      3
      Why not D: arr[2] = 8 and arr[3] = 1. The target 8 is found at index 2, not 3.
    Explanation

    The loop searches for value 8. At i=2, arr[2]==8, so index is set to 2. The loop continues but 8 doesn't appear again. Final index = 2.

    Key takeaway

    Linear search: scan each element, store the index when found. Initialize to -1 as a sentinel for 'not found'.

  10. Question 10 · Medium

    What is the output of the following code?

    int[] arr = {1, 2, 3, 4, 5};
    for (int i = 0; i < arr.length / 2; i++) {
        int temp = arr[i];
        arr[i] = arr[arr.length - 1 - i];
        arr[arr.length - 1 - i] = temp;
    }
    System.out.println(arr[0] + " " + arr[2] + " " + arr[4]);
    
    • A
      1 3 5
      Why not A: The code reverses the array in-place. After reversal: arr = {5, 4, 3, 2, 1}. arr[0]=5, arr[2]=3, arr[4]=1.
    • B
      5 3 1Correct
    • C
      5 4 3
      Why not C: arr[2] remains 3 (middle element is unchanged in odd-length reversal). arr[4]=1, not 3.
    • D
      1 2 3
      Why not D: The swap loop reverses the array. Elements are not unchanged after the loop.
    Explanation

    This is the classic in-place array reversal. Loop runs for i=0 and i=1 (length/2 = 2). i=0: swap arr[0] and arr[4] → {5,2,3,4,1}. i=1: swap arr[1] and arr[3] → {5,4,3,2,1}. arr[0]=5, arr[2]=3, arr[4]=1.

    Key takeaway

    In-place array reversal swaps element at index `i` with element at index `length-1-i`, looping only `length/2` times.

  11. Question 11 · Medium

    What is the output of the following code?

    int[] arr = {4, 2, 7, 1, 5};
    for (int i = 0; i < arr.length - 1; i++) {
        if (arr[i] > arr[i + 1]) {
            int temp = arr[i];
            arr[i] = arr[i + 1];
            arr[i + 1] = temp;
        }
    }
    System.out.println(arr[0] + " " + arr[1]);
    
    • A
      4 2
      Why not A: 4 > 2, so they swap. After i=0: arr = {2, 4, ...}. arr[0] = 2.
    • B
      2 4Correct
    • C
      1 2
      Why not C: This is only one pass of bubble sort. Only adjacent pairs where left > right are swapped in this single pass. The array after one pass is {2, 4, 1, 5, 7} — arr[0]=2, arr[1]=4.
    • D
      2 1
      Why not D: Trace carefully: i=0(4>2→swap→{2,4,7,1,5}), i=1(4<7→no swap), i=2(7>1→swap→{2,4,1,7,5}), i=3(7>5→swap→{2,4,1,5,7}). arr[0]=2, arr[1]=4.
    Explanation

    One pass of bubble sort. i=0: 4>2, swap → {2,4,7,1,5}. i=1: 4<7, no swap. i=2: 7>1, swap → {2,4,1,7,5}. i=3: 7>5, swap → {2,4,1,5,7}. arr[0]=2, arr[1]=4.

    Key takeaway

    One bubble sort pass moves the largest element to the end. The loop bound is `arr.length - 1` to avoid comparing arr[last] with arr[last+1].

  12. Question 12 · Medium

    What is the output of the following code?

    String[] words = {"cat", "bird", "ant", "dog"};
    String first = words[0];
    for (String w : words) {
        if (w.compareTo(first) < 0) {
            first = w;
        }
    }
    System.out.println(first);
    
    • A
      cat
      Why not A: compareTo returns negative when the argument comes AFTER first alphabetically. "ant" < "cat" alphabetically, so first updates to "ant".
    • B
      antCorrect
    • C
      dog
      Why not C: "dog" comes after "cat" alphabetically, so "dog".compareTo("cat") > 0. first doesn't update to "dog".
    • D
      bird
      Why not D: "bird" < "cat" alphabetically, but "ant" < "bird" too. The algorithm finds the lexicographically smallest string.
    Explanation

    String.compareTo returns negative if the calling string comes before the argument alphabetically. Trace: first="cat". "cat" (no change, same). "bird" < "cat" → first="bird". "ant" < "bird" → first="ant". "dog" > "ant" → no change. final first="ant".

    Key takeaway

    `s1.compareTo(s2)` returns negative if s1 < s2 lexicographically. Use it to find min/max strings the same way you find min/max numbers.