Post

Created by @nathanedwards
 at November 1st 2023, 2:58:59 pm.

AP Computer Science Exam Question

Consider the following code:

import java.util.ArrayList;

public class ArrayListOperations {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(2);
        numbers.add(4);
        numbers.add(6);
        numbers.add(8);
        numbers.add(10);

        numbers.add(2, 20);
        
        numbers.remove(3);
        
        System.out.println(numbers.get(1));
        System.out.println(numbers.size());
        System.out.println(numbers.contains(4));
    }
}

What is the output of the above code?

  1. 2
  2. 5
  3. true

Explain each step of the code and how the ArrayList operations affect the elements stored in the ArrayList.

Answer with Step-by-Step Explanation

The output of the code is:

4
5
true

Explanation:

  1. The ArrayList numbers is created and initialized with values [2, 4, 6, 8, 10] using the numbers.add() method.

  2. The numbers.add(2, 20) operation adds the element 20 at index 2. After this operation, the ArrayList numbers becomes [2, 4, 20, 6, 8, 10].

  3. The numbers.remove(3) operation removes the element at index 3. After this operation, the ArrayList numbers becomes [2, 4, 20, 8, 10].

  4. The numbers.get(1) operation retrieves the element at index 1, which is 4. This value is printed to the console.

  5. The numbers.size() operation returns the size of the ArrayList, which is 5. This value is printed to the console.

  6. The numbers.contains(4) operation checks if the ArrayList contains the element 4. Since 4 is present in the ArrayList, the contains method returns true. This value is printed to the console.

Thus, the output of the code is 4, 5, true.