Java OCA OCP Practice Question 1671

Question

What is the output of the following application?

package mypkg;/*from   w w  w  .  j a v  a  2  s.  c om*/
import java.util.function.*;


public class Main {
   private int c;
   private static class ConvertToCents {
      static DoubleToIntFunction f = p -> p*100;
   }
   public static void main(String... currency) {
      Main main = new Main();
      main.c = 100;
      double deposit = 1.5;

      main.c += ConvertToCents.f.applyAsInt(deposit);  // j1

      System.out.print(main.c);
   }
}
  • A. 200
  • B. 250
  • C. The code does not compile because of line j1.
  • D. None of the above


D.

Note

The code does not compile because the lambda expression p -> p*100 is not compatible with the DoubleToIntFunction functional interface.

The input to the functional interface is double, meaning p*100 is also double.

The functional interface requires a return value of int, and since double cannot be implicitly cast to int, the code does not compile, making Option D the correct answer.

If the correct cast was applied to make (p*100) an int, then the rest of the class would compile and 250 would be printed at runtime, making Option B correct.




PreviousNext

Related