AP Exams AP Computer Science A

AP Computer Science A Practice Test: Arrays and ArrayList

  • Arrays and ArrayList
  • 10 questions
  • 15 minutes

Ten Java code-tracing questions on arrays and ArrayList. Tip: write down the contents of the array or list after every statement instead of tracing in your head.

Tap an option to mark your answer. You can change your mind, or tap the same option again to leave the question blank. The correct answers and explanations appear when you finish the test.Tap an option to answer; tap it again to leave the question blank.

Advertisement
Advertisement
  1. Question 1

    int[] a = {4, 8, 15, 16, 23};
    int s = 0;
    for (int i = 1; i < a.length; i += 2)
    {
       s += a[i];
    }
    System.out.println(s);

    What is printed?

  2. Question 2

    ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(5); list.add(10); list.add(15); list.add(20);
    list.remove(1);
    list.add(1, 7);
    list.set(2, list.get(2) + 1);
    System.out.println(list);

    What is printed?

  3. Question 3

    ArrayList<Integer> nums = new ArrayList<Integer>();
    nums.add(2); nums.add(4); nums.add(4); nums.add(6); nums.add(8);
    for (int i = 0; i < nums.size(); i++)
    {
       if (nums.get(i) == 4)
       {
          nums.remove(i);
       }
    }
    System.out.println(nums);

    What is printed?

  4. Question 4

    int[] arr = new int[5];
    for (int i = 0; i <= arr.length; i++)
    {
       arr[i] = i * 2;
    }

    What happens when this code runs?

  5. Question 5

    int[] nums = {1, 2, 3};
    for (int n : nums)
    {
       n = n * 2;
    }
    System.out.println(nums[0] + nums[1] + nums[2]);

    What is printed?

  6. Question 6

    public static int mystery(int[] a)
    {
       int c = 0;
       for (int i = 0; i < a.length - 1; i++)
       {
          if (a[i] > a[i + 1])
          {
             c++;
          }
       }
       return c;
    }

    What is returned by mystery(new int[] {3, 1, 4, 1, 5, 9, 2, 6})?

  7. Question 7

    int[] r = {1, 2, 3, 4};
    for (int i = 0; i < r.length; i++)
    {
       int temp = r[i];
       r[i] = r[r.length - 1 - i];
       r[r.length - 1 - i] = temp;
    }

    What are the contents of r after the loop?

  8. Question 8

    ArrayList<String> w = new ArrayList<String>();
    w.add("ant"); w.add("bee"); w.add("cat");
    for (int i = 0; i < w.size(); i++)
    {
       w.set(i, w.get(i) + i);
    }
    System.out.println(w);

    What is printed?

  9. Question 9

    Which of the following statements compiles without error in Java?

  10. Question 10

    int[] p = {2, 5, 9};
    int[] q = p;
    q[0] = 100;
    System.out.println(p[0]);

    What is printed?

Questions you leave blank are not counted as wrong.

Advertisement
15:00

Do you want to finish the test?