Java OCA OCP Practice Question 1555

Question

Which lambda expression can replace the instance of new Movie() in the Main class and produce the same results under various inputted values?

package mypkg;/*  w w  w . j av a  2  s  . c o  m*/
 
@FunctionalInterface 
interface Printable {
   abstract int print(String subject, int duration);
}
 
class Movie implements Printable {
   @Override public int print(String subject, int duration) {
      if(subject == null)
         return duration;
      else
         return duration+1;
   }
}
 
public class Main {
   public static void main(String[] courses) {
      final Printable s = new Movie() {};
      System.out.print(s.print(courses[0], Integer.parseInt(courses[1])));
   }
}
  • A. (p,q) -> q==null ? p : p+1
  • B. (c,d) -> {int d=1; return c!=null ? d+1 : d;}
  • C. (x,y) -> {return x==null ? y : y+1;}
  • D. None of the above


C.

Note

Option A does not compile since the variables p and q are reversed, making the return type of the method and usage of operators invalid.

The first argument p is a String and q is an int, but the lambda expression reverses them, and the code does not compile.

Option B also does not compile.

The variable d is declared twice, first in the lambda argument list and then in the body of the lambda expression.

The second declaration in the body of the lambda expression causes the compiler to generate a duplicate local variable message.

Option C is the correct answer since it compiles and handles the input in the same way as the print() method in the Movie class.




PreviousNext

Related