Post

Created by @nathanedwards
 at November 3rd 2023, 1:25:20 pm.

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:

  1. Four names ("John", "Anna", "Peter", "Emily") are added to the ArrayList using the add() method.
  2. The name "David" is inserted at index 2 in the ArrayList using the add(int index, E element) method. After this step, the ArrayList will be: [John, Anna, David, Peter, Emily].
  3. The second name ("Anna") is removed from the ArrayList using the remove(int index) method. After this step, the ArrayList will be: [John, David, Peter, Emily].
  4. The name at index 3 ("Emily") is replaced with "Sophia" using the 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].