nerdexam
Oracle

1Z0-809 · Question #146

Given the code fragment: 13. list colors = new ArrayList<>(); 14. colors.add("green"); 15. colors.add("red"); 16. colors.add("blue"); 17. colors.add("yellow"); 18. colors.remove(2); 19…

The correct answer is D. [green, red, yellow, cyan]. There is an error in this question's stated answer - tracing the code reveals the output is actually A, not D. Here is the step-by-step trace: | Line | Operation | List state | |------|-----------|------------| | 14–17 | Four add() calls | [green, red, blue, yellow] | | 18 |…

Question

Given the code fragment:
  1. list colors = new ArrayList<>();
  2. colors.add("green");
  3. colors.add("red");
  4. colors.add("blue");
  5. colors.add("yellow");
  6. colors.remove(2);
  7. colors.add(2, "cyan");
  8. System.out.print(colors);
What is the result?

Options

  • A[green, red, cyan, yellow]
  • BAn IndexOutOfBoundsException is thrown at runtime.
  • C[green, blue, yellow, cyan]
  • D[green, red, yellow, cyan]

How the community answered

(40 responses)
  • A
    8% (3)
  • B
    5% (2)
  • C
    15% (6)
  • D
    73% (29)

Explanation

There is an error in this question's stated answer - tracing the code reveals the output is actually A, not D. Here is the step-by-step trace:

LineOperationList state
14–17Four add() calls[green, red, blue, yellow]
18remove(2) - removes element at index 2 ("blue")[green, red, yellow]
19add(2, "cyan") - inserts "cyan at index 2, shifting "yellow" right[green, red, cyan, yellow]
20System.out.print(colors)prints [green, red, cyan, yellow]

Why A is actually correct: ArrayList.remove(int index) removes by position (not by value), so remove(2) deletes "blue". Then add(2, "cyan") inserts at index 2, pushing "yellow" to index 3 - yielding [green, red, cyan, yellow].

Why the distractors fail:

  • B - no exception is thrown; index 2 is valid at both lines 18 and 19.
  • C - would require remove(1) (removing "red"), not remove(2).
  • D - would be correct only if line 19 were colors.add("cyan") (no index argument), which appends to the end.

Memory tip: With ArrayList, add(i, val) inserts (shifts right) and remove(i) deletes (shifts left) - both operate on a zero-based index. When an exam shows both on consecutive lines, redraw the list state after each call to avoid mixing them up.

Note for the exam taker: If this question appears on your actual exam with answer D marked correct, the answer key likely contains a typo on line 19 (it should read colors.add("cyan") without an index). Raise it with your instructor.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice