Java - Static Method References

Introduction

A static method reference uses a static method as a lambda expression.

The type could be a class, an interface, or an enum.

The following static method of the Integer class:

static String toBinaryString(int i)

It represents a function that takes an int as an argument and returns a String.

You can use it in a lambda expression as shown:

import java.util.function.Function;

public class Main {
  public static void main(String[] args) {
    Function<Integer, String> func1 = x -> Integer.toBinaryString(x);
    System.out.println(func1.apply(17));
  }
}

You can rewrite this statement using a static method reference, as shown:

Function<Integer, String> func2 = Integer::toBinaryString;
System.out.println(func2.apply(17));

The compiler finds a static method toBinaryString() from Integer class.

The it verifies that toBinaryString() method takes an int as an argument and returns a String.

The target type of the method reference is a function that takes an Integer as an argument and returns a String.

The compiler verifies that the method reference and target type are assignment compatible.

Related Topics

Quiz