AP Computer Science A · Topic 6.1

Array Creation and Access Practice

Part of Array.

Practice questions

24

Want a predicted score for the whole AP CSA exam? Take the 20-question diagnostic and Lumi will plan the rest.

Sample questions

5 of 24 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. Sample 1difficulty 1/5

    int[] a = new int[5];
    int sum = 0;
    for (int x : a) {
      sum += x;
    }
    System.out.println(sum);

    What is printed?

    • A

      ArrayIndexOutOfBoundsException

    • B

      5

    • C

      null

    • D

      0

      check_circle

    Why

    new int[5] initializes all 5 elements to 0. Their sum is 0.

  2. Sample 2difficulty 2/5

    For <code>int[] a = {10, 20, 30};</code>, <code>a[1]</code> is

    • A

      20

      check_circle
    • B

      Out of bounds

    • C

      10

    • D

      30

    Why

    Index 1 is the SECOND element (20).

  3. Sample 3difficulty 2/5

    int[] a;
    a[0] = 1;

    What is wrong?

    • A

      Arrays cannot be declared without size

    • B

      Index 0 is reserved

    • C

      Nothing is wrong

    • D

      a is declared but not instantiated; you must allocate with new int[size]

      check_circle

    Why

    Declaring int[] a only creates a reference variable. You must allocate the array with a = new int[n] before assigning elements.

  4. Sample 4difficulty 2/5

    int[] a = {10, 20, 30, 40};
    System.out.println(a[2]);

    What is printed?

    • A

      30

      check_circle
    • B

      20

    • C

      40

    • D

      2

    Why

    Arrays are 0-indexed, so a[0]=10, a[1]=20, a[2]=30, a[3]=40. Index 2 is the third element, 30.

  5. Sample 5difficulty 2/5

    int[] a = {3, 1, 4, 1, 5};
    System.out.println(a.length);

    What is printed?

    • A

      4

    • B

      6

    • C

      0

    • D

      5

      check_circle

    Why

    The initializer list has 5 elements, so a.length is 5. Note: array length uses the field a.length (no parentheses), not the method a.length().

AP Computer Science A · 6.1 Array Creation and Access — Practice Questions | Acemy