Post

Created by @nathanedwards
 at November 3rd 2023, 5:01:19 am.

Question:

Consider the following code snippet:

import java.util.ArrayList;

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

        numbers.add(10);
        numbers.add(20);
        numbers.add(30);

        numbers.remove(1);

        System.out.println(numbers);
    }
}

What will be the output of the above code?

A) [10, 20]
B) [10, 30]
C) [20, 30]
D) [10, 20, 30]

Explain your answer and the steps involved in the code execution.

Answer:

The output of the given code will be:

B) [10, 30]

Explanation:

  1. We start by creating an instance of the ArrayList class named numbers using the ArrayList<Integer> syntax.
  2. We then add three elements to the numbers list using the add() method: 10, 20, and 30. The order of addition is preserved.
  3. The remove() method is used to remove the element at index 1 from the numbers list. In this case, the element 20 is removed.
  4. Finally, the System.out.println() statement is used to print the contents of the numbers list. Since the element 20 was removed, the output will be [10, 30].

Therefore, the correct answer is B) [10, 30].