ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
List<String> l = Arrays.asList("b", null, "a");
l.sort(Comparator.nullsFirst(Comparator.naturalOrder()));
System.out.print(l);
  1. A. [a, b, null]
  2. B. A NullPointerException is thrown
  3. C. [null, a, b]
  4. D. [b, null, a]

Correct answer: C. [null, a, b]

nullsFirst wraps a comparator so that null is treated as smaller than every non-null value; the non-null elements use natural order. Plain natural order would throw NullPointerException.

More OOP with C++ and Java questions

Exams that ask this topic