Question:
Given the following code snippet:
import java.util.ArrayList;
public class ArrayListOperations {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<String>();
// Add names to the ArrayList
names.add("John");
names.add("Anna");
names.add("Peter");
names.add("Emily");
// Insert a new name at index 2
names.add(2, "David");
// Remove the second name from the ArrayList
names.remove(1);
// Replace the fourth name with "Sophia"
names.set(3, "Sophia");
// Print the final ArrayList
System.out.println(names);
}
}
What will be the output of the given code?
A) [John, Peter, Emily, Sophia] B) [John, David, Peter, Emily, Sophia] C) [John, David, Peter, Sophia] D) [John, Anna, Peter, Emily, Sophia]
Explain your answer and provide a step-by-step detailed explanation.
Answer:
The correct answer is C) [John, David, Peter, Sophia].
The given code defines an ArrayList called names
and performs various operations on it:
add()
method.add(int index, E element)
method. After this step, the ArrayList will be: [John, Anna, David, Peter, Emily].remove(int index)
method. After this step, the ArrayList will be: [John, David, Peter, Emily].set(int index, E element)
method. After this step, the ArrayList will be: [John, David, Peter, Sophia].Thus, the final ArrayList will be [John, David, Peter, Sophia].