Question:
Consider the following code snippet:
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("David");
names.remove(1);
for (String name : names) {
System.out.println(name);
}
}
}
What is the output of the above code snippet?
A) Alice B) Bob C) Charlie D) David E) The code will fail to compile due to an error
Explain your answer choice step-by-step.
Answer:
The output of the above code snippet will be:
Alice
Charlie
David
Explanation:
In the given code snippet, an ArrayList named names
is created to store strings. The elements "Alice", "Bob", "Charlie", and "David" are added to the names
ArrayList using the add()
method in the order they are specified.
Next, the remove()
method is called on the names
ArrayList with the index 1 provided as the parameter. This will remove the element at index 1, which is "Bob".
After the removal of "Bob", the for
loop is used to iterate over the remaining elements of the names
ArrayList. The loop will execute three times, printing each element on a new line using the println()
method.
Therefore, the output of the code snippet will be "Alice", "Charlie", and "David", printed each on a separate line.
Hence, the correct answer is:
A) Alice C) Charlie D) David