Java OCA OCP Practice Question 1589

Question

What is the result of the following?

6:   List<String> list = new ArrayList<>();
7:   list.add("Monday");
8:   list.add(String::new);
9:   list.add("Tuesday");
10:  list.remove(0);
11:  System.out.println(list.get(0));
  • A. An empty String
  • B. Monday
  • C. The code does not compile.
  • D. The code compiles but throws an exception at runtime.


C.

Note

Line 8 does not compile.

String::new is a constructor reference.

A constructor or method reference is equivalent to a lambda.

It participates in deferred execution.

When it is executed later, it returns a String.

It does not return a String on line 8.

It returns a Supplier<String>, which cannot be stored in list.

Since the code does not compile, Option C is correct.




PreviousNext

Related