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:
ArrayList
class from the java.util
package and creating a new ArrayList
object named students
to store a list of student records.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.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".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.students
list are printed using the System.out.println()
statement.The order of execution can be summarized as follows:
Therefore, the output will be [John Smith, Michelle Thompson, Jane Doe, Emily Brown].