Java - What is the output: Static Method References?


What is the output of the following code?

import java.util.function.Function;

public class Main {
  public static void main(String[] args) {
    Function<Integer, Integer> func = Integer::sum; 

Click to view the answer

Function func = Integer::sum; // A compile-time error


Consider another static method sum() in the Integer class:

static int sum(int a, int b)

The method reference would be Integer::sum.

The compiler generates the following error message when you compile this code:

Error: incompatible types: invalid method reference
                Function<Integer, Integer> func = Integer::sum;
method sum in class Integer cannot be applied to given types
required: int,int
found: Integer
reason: actual and formal argument lists differ in length

Integer::sum is not assignment compatible with the target type Function<Integer, Integer>.

The sum(int, int) method takes two int arguments whereas the target type takes only one Integer argument.

The mismatch in the number of arguments caused the compile-time error.

To fix the error, use a BiFunction<Integer, Integer, Integer> as the target type.


import java.util.function.BiFunction;

public class Main {
  public static void main(String[] args) {
    // Uses a lambda expression
    BiFunction<Integer, Integer, Integer> func1 = (x, y) -> Integer.sum(x, y);
    System.out.println(func1.apply(7, 5));

    // Uses a method reference
    BiFunction<Integer, Integer, Integer> func2 = Integer::sum;
    System.out.println(func2.apply(7, 5));

  }//from  w  w w.  jav a  2  s  . co m


Related Quiz