This is an original sample question written by itmoshi based on the exam objectives.
Show answer and explanation
Answer:C It prints [9, 8, 3] [9, 2, 3], then b.set(2, 7) throws an UnsupportedOperationException.
Why it is correct
The list returned by Arrays.asList has a fixed size but allows set, so a becomes [9, 2, 3]. List.copyOf returns an unmodifiable list holding a copy of the elements at that moment, so b stays [9, 2, 3] and is not affected by the later a.set(1, 8). The first line printed is therefore [9, 8, 3] [9, 2, 3]. Calling set on the unmodifiable b then throws UnsupportedOperationException, so the second println never runs.
The other options
- ✗ A What an Arrays.asList list forbids is changing its size with add or remove; set is allowed. The exception appears only when you try to change the size.
- ✗ B This treats b as a view of a. Given an Arrays.asList source as in this example, List.copyOf returns an unmodifiable snapshot of its current contents, so later replacements in a do not show up in b. If you want changes to the original to be visible, use a view such as Collections.unmodifiableList.
- ✗ D The list returned by List.copyOf is unmodifiable, so both set and add throw UnsupportedOperationException. For a modifiable copy, use new ArrayList<>(a).
Key takeaway
Arrays.asList → fixed size (set OK, add/remove not). List.of / List.copyOf → unmodifiable (no set either); a copyOf result does not reflect later additions, removals, or replacements in the source. Collections.unmodifiableList → unmodifiable view (changes to the original show through).