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
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:
Initialization: ArrayList<Integer> numbers = new ArrayList<>();
ArrayList named numbers that can store Integer objects.Adding elements to the ArrayList: for (int i = 0; i < 5; i++) { numbers.add(i); }
numbers list.Inserting an element: numbers.add(3, 10);
numbers list, shifting the existing elements to the right.Removing an element: numbers.remove(2);
numbers list, shifting the remaining elements to the left.Printing an element: System.out.println(numbers.get(4));
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.