Post

Created by @nathanedwards
 at October 31st 2023, 5:56:00 pm.

Question:

Consider the following code snippet:

ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(10);
numbers.add(15);
numbers.add(20);

numbers.set(2, 25);
numbers.remove(1);
numbers.add(0, 30);

System.out.println(numbers.get(3));

What is the output that will be printed to the console when the above code is executed? Provide a step-by-step explanation of the code to arrive at the output.

Answer:

The output that will be printed to the console when the above code is executed is:

25

Step-by-step explanation of the code:

  1. We declare an ArrayList called numbers that stores integers.
  2. We add the values 5, 10, 15, and 20 to the numbers ArrayList using the add() method.
  3. The set() method is used to replace the element at index 2 with the value 25. So, the ArrayList now contains 5, 10, 25, and 20.
  4. The remove() method is used to remove the element at index 1. After removing, the ArrayList contains 5, 25, and 20.
  5. The add() method is used to add the value 30 at index 0. So, the final ArrayList contains 30, 5, 25, and 20.
  6. Finally, System.out.println(numbers.get(3)) prints the value at index 3, which is 20.

Therefore, the output printed to the console is 25.