Java OCA OCP Practice Question 2188

Question

Which of the following expressions, inserted simultaneously into both blanks, allow the application to compile? (Choose three.)

package mypkg; /*from w ww  . ja v  a 2 s.  c  o  m*/
import java.util.function.*; 
abstract class Printer { 
   public void print(DoubleConsumer c, double value) { 
      c.accept(value); 
   } 
} 
public class ConsolePrinter extends Printer { 
   public void bustNow(Consumer<Double> c, double value) { 
      c.accept(value); 
   } 
   void call() { 
      double value = 10; 
      bustNow(___,value); 
      print(___,value); 
   } 
} 
  • A. System.out::print
  • B. a -> {System.out.println(a.intValue());}
  • C. g -> {System.out.println();}
  • D. u -> System.out.println((long)u)
  • E. v -> System.out.print(v)
  • F. w -> System.out::println


A, C, E.

Note

To start with, bustNow() now takes a Double value, while print() takes a double value.

To be compatible, the lambda expression has to be able to handle both data types.

Option A is correct, since the method reference System.out::print matches overloaded methods that can take double or a Double (via unboxing).

Option B is incorrect, since intValue() works for the Consumer<Double>, which takes Double, but not DoubleConsumer, which takes double.

For a similar reason, Option D is also incorrect because only the primitive double is compatible with this expression.

Option C is correct and results in just a blank line being printed.

Option E is correct since it is just the lambda version of the method reference in Option A.

Finally, Option F is incorrect because of incompatible data types.

The method reference is being used inside of a lambda expression, which would only be allowed if the functional interface returned another functional interface reference.




PreviousNext

Related