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:
ArrayList class named numbers using the ArrayList<Integer> syntax.numbers list using the add() method: 10, 20, and 30. The order of addition is preserved.remove() method is used to remove the element at index 1 from the numbers list. In this case, the element 20 is removed.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].