Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard

Question 103

Question ID: UKOCP81279


Given code:


What is the result?

  • A 0
  • B 1
  • C 2
  • D Compilation error
Reveal correct answer

Correct answer: D

Explanation

UKOCP81279:

s -> s.add(10) an ambiguous call and it matches to 2nd argument of both the overloaded methods.

Consumer<Set<Integer>> consumer = s -> s.add(10);

and

Predicate<Set<Integer>> predicate = s -> s.add(10);


So, both Line n1 and Line n2 cause compilation error.


There are 3 ways to resolve the error:

1. Use the reference variable of particular type:

Consumer<Set<Integer>> consumer = s -> s.add(10);

add(set, consumer); //Line n1 => Matches to method at Line n3


Predicate<Set<Integer>> predicate = s -> s.add(20);

add(set, predicate); //Line n2 => Matches to method at Line n4


2. Typecast to exact type:

add(set, (Consumer<Set<Integer>>)s -> s.add(10)); //Line n1 => Matches to method at Line n3

add(set, (Predicate<Set<Integer>>)s -> s.add(20)); //Line n2 => Matches to method at Line n4


3. Use the lambda expression with body:

add(set, s -> {s.add(10); return;}); //Line n1 => Matches to method at Line n3

add(set, s -> {return s.add(20);}); //Line n2 => Matches to method at Line n4

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need