Post

Created by @nathanedwards
 at October 31st 2023, 6:59:08 pm.

AP Computer Science Exam Question:

Consider the following code snippet:

import java.util.ArrayList;

public class ArrayListExample {

    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();

        for (int i = 0; i < 5; i++) {
            numbers.add(i);
        }

        numbers.add(3, 10);

        numbers.remove(2);

        System.out.println(numbers.get(4));
    }
}

What will be the output of the above code?

[]

a) 0
b) 1
c) 2
d) 3
e) 4
f) 10

Explanation:

The given code creates an ArrayList of Integer objects named numbers. It then uses a for loop to add numbers from 0 to 4 to the numbers list. After that, the code inserts the number 10 at index 3 using the add() method. Then, the code removes the element at index 2 using the remove() method. Finally, it prints the element at index 4 using the get() method.

Let's analyze the code step by step:

  1. Initialization: ArrayList<Integer> numbers = new ArrayList<>();

    • This initializes an empty ArrayList named numbers that can store Integer objects.
  2. Adding elements to the ArrayList: for (int i = 0; i < 5; i++) { numbers.add(i); }

    • This loop adds the numbers from 0 to 4 to the numbers list.
  3. Inserting an element: numbers.add(3, 10);

    • This inserts the number 10 at index 3 of the numbers list, shifting the existing elements to the right.
  4. Removing an element: numbers.remove(2);

    • This removes the element at index 2 from the numbers list, shifting the remaining elements to the left.
  5. Printing an element: System.out.println(numbers.get(4));

    • This prints the element at index 4 of the numbers list, which is the final value after the previous modifications.

Based on the given code, the output will be:

4

Therefore, the correct option is e) 4.