Question 1
What is the output of the following program? ```java import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> l = new ArrayList<String>(); l.add("a"); l.add("b"); l.add(1, "c"); l.set(0, "d"); System.out.println(l + " " + l.size()); } } ```
A. [d, b, c] 3
This treats add(1, "c") as appending "c" at the end rather than inserting it at index 1. The insert shifts "b" right to give [a, c, b], so "c" is not last.
B. [d, c, b] 3Correct answer
add("a"), add("b") give [a, b]; add(1, "c") inserts at index 1 shifting "b" right to [a, c, b]; set(0, "d") replaces index 0 without changing size, giving [d, c, b] with size 3 (JavaDoc 7 — ArrayList.add(int, E) / set(int, E)).
C. [c, d, b] 3
This misplaces the inserted and replaced elements. "c" is inserted at index 1 (not index 0), and set(0, "d") replaces index 0, so "d" must be first, giving [d, c, b].
D. [d, c, b] 4
The contents are right, but set(0, "d") replaces an existing element rather than adding one, so the size stays 3, not 4. Only add grows the list.
Explanation
add("a"), add("b") → [a, b]. add(1, "c") INSERTS at index 1, shifting b right → [a, c, b]. set(0, "d") REPLACES the element at index 0 without changing the size → [d, c, b], size 3. add-with-index grows the list; set never does.