Post

Created by @nathanedwards
 at October 31st 2023, 7:48:42 pm.

AP Computer Science Exam Question:

Consider the following code snippet:

import java.util.ArrayList;

public class StudentRecords {
    public static void main(String[] args) {
        ArrayList<String> students = new ArrayList<>();

        students.add("John Smith");
        students.add("Jane Doe");
        students.add("Michael Johnson");
        students.add("Emily Brown");

        students.remove(2);
        students.add(2, "Michelle Thompson");

        System.out.println(students);
    }
}

What will be printed when the above code is executed?

A. [John Smith, Jane Doe, Emily Brown, Michelle Thompson] B. [John Smith, Jane Doe, Emily Brown] C. [John Smith, Michelle Thompson, Jane Doe, Emily Brown] D. [John Smith, Jane Doe, Michelle Thompson, Emily Brown]

Explain your answer and provide a step-by-step explanation of the code execution.

Answer:

The correct answer is C. [John Smith, Michelle Thompson, Jane Doe, Emily Brown].

Explanation:

  • The code snippet begins by importing the ArrayList class from the java.util package and creating a new ArrayList object named students to store a list of student records.
  • Four student names are then added to the students list using the add() method: "John Smith", "Jane Doe", "Michael Johnson", and "Emily Brown". The order in which they are added determines their index positions in the list, with "John Smith" at index 0, "Jane Doe" at index 1, "Michael Johnson" at index 2, and "Emily Brown" at index 3.
  • The remove() method is called on the students list, passing the index 2 as the argument. This removes the student name at index 2, which is "Michael Johnson".
  • The add() method is then called on the students list again to insert the name "Michelle Thompson" at index 2. This shifts the original names "Jane Doe" and "Emily Brown" to index positions 3 and 4, respectively.
  • Finally, the contents of the students list are printed using the System.out.println() statement.

The order of execution can be summarized as follows:

  1. Initial state: [John Smith, Jane Doe, Michael Johnson, Emily Brown]
  2. Remove item at index 2: [John Smith, Jane Doe, Emily Brown]
  3. Insert "Michelle Thompson" at index 2: [John Smith, Michelle Thompson, Jane Doe, Emily Brown]
  4. Print the final result: [John Smith, Michelle Thompson, Jane Doe, Emily Brown]

Therefore, the output will be [John Smith, Michelle Thompson, Jane Doe, Emily Brown].