nerdexam
Oracle

1Z0-819 · Question #151

Given the code fragment: public static void main(String[] args) { var even = List.of(1, even.add(-1); even.add(0, -2); even.add(0, -2); System.out.println(even); } What is the output?

The correct answer is D. A runtime exception is thrown. List.of() creates an immutable, fixed-size list. While add() is defined on the List interface (so the code compiles), calling it on a List.of() result throws an UnsupportedOperationException at runtime - making D correct. Why the distractors are wrong: A (compilation fails)…

Working with Arrays and Collections

Question

Given the code fragment: public static void main(String[] args) { var even = List.of(1, even.add(-1); even.add(0, -2); even.add(0, -2); System.out.println(even); } What is the output?

Options

  • AThe compilation fails.
  • B[1,-1]
  • C[-3,-2,-1]
  • DA runtime exception is thrown.

How the community answered

(31 responses)
  • A
    3% (1)
  • B
    10% (3)
  • C
    13% (4)
  • D
    74% (23)

Explanation

List.of() creates an immutable, fixed-size list. While add() is defined on the List interface (so the code compiles), calling it on a List.of() result throws an UnsupportedOperationException at runtime - making D correct.

Why the distractors are wrong:

  • A (compilation fails): The code compiles because var infers the type as List<Integer>, which declares add() in its interface. Immutability is a runtime constraint, not a compile-time one.
  • B [1,-1]: Would only be possible if the first add(-1) succeeded - it doesn't; the list is unmodifiable.
  • C [-3,-2,-1]: Would require all three mutation calls to succeed, which is impossible on a List.of() list.

Memory tip: Think of List.of() as "List. Off-limits." It compiles fine because the compiler only checks the interface contract, but any write operation is blocked at runtime. If you need a mutable list, use new ArrayList<>(List.of(...)).

Topics

#List.of() immutability#UnsupportedOperationException#Immutable collections#Runtime exceptions

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice