Before looking into what is method reference let’s understand about java Double colon (::) operator, because method references always utilize double colon (::) operator.

The double colon operator (::) introduced in Java 8, the java double colon (::) operator, also known as method reference operator in Java, is used to call a method by referring to it with the help of its class directly. They behave exactly as the lambda expressions. The only difference it has from lambda expressions is that this uses direct reference to the method by name instead of providing a delegate to the method.

What is method reference ?

To create lambda expressions we use anonymous methods. Some times the implementation that you want to create in lambda is already available in existing method. In those cases method references enable you to refer functional interface method by name in place of lambda expressions.

Our specified method can be either static method or instance method. Functional interface method and our specified method should have same argument and compatible return types, except this remaining things like method name, modifiers are not required to match.

Method references always utilize double colon (::) operator.

Types of method references :

  1. Reference to static method.
  2. Reference to an instance method of a particular object.
  3. Reference to an instance method of an arbitrary object of a particular type

To define method reference we have to use :: (double colon) operator.

1.Reference to static method

You can refer to static method defined in the class. Following is the syntax and example which describe the process of referring static method in Java.

Syntax:

Example with lambda expression :

Same example with method reference :

2.Reference to an instance method

Like static methods, you can refer instance methods also. In the following example, we are describing the process of referring the instance method.

Syntax:

Reference to instance method example

3.Reference to an instance method of an arbitrary object of a particular type

Like static methods, you can refer instance methods also. In the following example, we are describing the process of referring the instance method.

Syntax:

 

This type of method references are little confusing. If you look into the example String::toUpperCase, usually toUpperCase() method is called on a string reference but we have written class name “String” as like it is a static method. When we use method references they also go through similar checks as lambda expression goes. Compiler will try to match the method reference with any of functional descriptor syntax and if matches then passes on.

Example