Java OCA OCP Practice Question 1649

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 static int LENGTH = 100;
   public int takeTicket(int currentCount, IntUnaryOperator<Integer> counter) {
      return counter.applyAsInt(currentCount);
   }
   public static void main(String...theater) {
      final Main bob = new Main();
      final int oldCount = 50;
      final int newCount = bob.takeTicket(oldCount,t -> {
         if(t>LENGTH) {
            throw new RuntimeException("Sorry, max has been reached");
         }
         return t+1;
      });
      System.out.print(newCount);
   }
}
  • A. 51
  • B. The code does not compile because of lambda expression.
  • C. The code does not compile for a different reason.
  • D. The code compiles but prints an exception at runtime.


C.

Note

The code does not compile, so Options A and D are incorrect.

The IntUnaryOperator functional interface is not generic, so the argument IntUnaryOperator<Integer> in the takeTicket() does not compile, making Option C the correct answer.

The lambda expression compiles without issue, making Option B incorrect.

If the generic argument <Integer> was dropped from the argument declaration, the class would compile without issue and output 51 at runtime, making Option A the correct answer.




PreviousNext

Related