What happens when the Java code List<Integer> x = List.of(1, 2); x.add(3); is run?
Correct answer C. An UnsupportedOperationException is thrown
Explanation
The factory method List.of returns an unmodifiable list, so any mutator such as add or remove throws UnsupportedOperationException. The code compiles because add is declared on the List interface. To obtain a list that can grow, copy the values into a modifiable implementation, for example new ArrayList(List.of(1, 2)).
Answer checked How we write and check questions
Discussion