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)…
Question
Options
- AThe compilation fails.
- B[1,-1]
- C[-3,-2,-1]
- DA runtime exception is thrown.
How the community answered
(31 responses)- A3% (1)
- B10% (3)
- C13% (4)
- D74% (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
varinfers the type asList<Integer>, which declaresadd()in its interface. Immutability is a runtime constraint, not a compile-time one. - B
[1,-1]: Would only be possible if the firstadd(-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 aList.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
Community Discussion
No community discussion yet for this question.