nerdexam
Oracle

1Z0-819 · Question #185

Given: public class Main { public static void main(String[] args) { List<String> list1 = new ArrayList<>(); list1.add("Plane"); list1.add("Automobile"); list1.add("Motorcycle"); List<String> list2 =…

The correct answer is A. A `java.lang.UnsupportedOperationException` is thrown. List.copyOf(list1) returns an unmodifiable list, and calling .sort() on an unmodifiable list triggers UnsupportedOperationException at runtime - this is the key trap. However, there's an important nuance here: the code wraps List.copyOf(list1) in new ArrayList<>(...), which…

Question

Given: public class Main { public static void main(String[] args) { List<String> list1 = new ArrayList<>(); list1.add("Plane"); list1.add("Automobile"); list1.add("Motorcycle"); List<String> list2 = new ArrayList<>(List.copyOf(list1)); list1.sort((String item1, String item2) -> item1.compareTo(item2)); list2.sort((String item1, String item2) -> item1.compareTo(item2)); System.out.println(list1.equals(list2)); } } What is the result?

Options

  • AA java.lang.UnsupportedOperationException is thrown.
  • BTrue
  • CFalse
  • DA java.lang.NullPointerException is thrown.
  • EThe compilation fails.

How the community answered

(57 responses)
  • A
    82% (47)
  • B
    11% (6)
  • C
    2% (1)
  • D
    4% (2)
  • E
    2% (1)

Explanation

List.copyOf(list1) returns an unmodifiable list, and calling .sort() on an unmodifiable list triggers UnsupportedOperationException at runtime - this is the key trap. However, there's an important nuance here: the code wraps List.copyOf(list1) in new ArrayList<>(...), which actually produces a mutable ArrayList, meaning .sort() on list2 would not throw in practice. This suggests the exam either has a transcription error (the wrapper should be absent: List<String> list2 = List.copyOf(list1);) or an incorrect answer key - with the code exactly as shown, B (true) is what the JVM would actually print, since both lists sort to ["Automobile", "Motorcycle", "Plane"] and ArrayList.equals() compares element-by-element.

Why the distractors are wrong (assuming the intended code lacks the new ArrayList<>() wrapper):

  • B (true) and C (false) are both wrong because execution never reaches the equals() call - the exception halts it first.
  • D (NullPointerException) is wrong because no null values exist in either list.
  • E (compilation fails) is wrong because the code is syntactically valid; the error is purely at runtime.

Memory tip: Think "Copy = Locked." List.copyOf() and List.of() both produce unmodifiable lists - any mutating call (add, remove, sort, set) throws UnsupportedOperationException. Wrapping them in new ArrayList<>(...) is the escape hatch that restores mutability.

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice