Method Reference in Java 8: Explained With Examples

The term method is used to define a collection of statements that perform any defined specific task. The result of the task performed by the statements in a method is returned to the user. The statements can be reused again in any other program where the same function of the task has to be carried out. These methods in Java8 can be treated as primitive values or objects and can be treated as variables. A new feature is provided in Java8, where any method having functional importance can be referred to. This special feature is known as the Method reference in Java8.

Java 8 is a type of release of the Java platform. The original Java programming was upgraded to another version where several features coordinate together, such as the JVM, libraries, and the Java language. The version of Java 8 is provided with the features for better productivity, easy use, and improvement in polyglot programming, improved performance, and high security. It serves as a great platform for intelligent devices and even a better choice for the developers to build up new services. In this version of Java, the Java 8, a method can be referred from a class or from an object through a specific syntax. 

Method reference in Java8

Usually, lambda expressions are used for creating anonymous methods. But there are times when the lambda expression doesn’t function; instead, they are used to call a method that already exists. Whenever the existing method is called, it is better than the method referred to by its name. Through the use of method references, the lambda expressions can call the methods which already exist. Mainly because of its compactness and better readability, the method references are being used. 

Before the release of Java 8, no methods were able to be passed as parameters. In such cases, if a method has to be passed, an object is required to be passed that contains the method. But, through the upgrade of the language, the methods are now being able to be passed as parameters. 

Therefore, method reference can be defined as some special form of the lambda expression. It is mainly because, in this case, the lambda expressions are not involved in doing any task, but rather it is involved in invoking the methods which exist. So a method can be referred to by the lambda expression in Java8. It helps reduce the code of the program and aids in supporting the newly developed functionality of the programming language. It is used for referring to a method that serves to be functionally important. 

As lambda expressions help reduce the code compared to any anonymous classes, the method references acts as the next step for the lambda expression. But like the lambda expressions, the method reference can execute only a single method. 

The following points can be marked while understanding the concept:

  • The method is referred to through the use of “::”.
  • The arguments for the method type are inferred upon by JRE at the runtime through the context it is defined.

For example, if the lambda expression looks like the way as shown below:

SourceSource 

In the above line of code, it can be noted that the user has used the operator “::.” This operator is used in the method reference to separate the object or the class from the method’s name. 

The lambda expressions are sometimes used only for calling a method that existed before. So, it is clear that in such scenarios, the method can be called by referring to the method by name. This is as mentioned is done by the method reference. Therefore, these method references can be considered as shorthand syntaxes for the lambda expression, which consists of only one call for the method. 

Syntax of a method reference

The general syntax of a method reference is shown below.

Object :: methodName

The above syntax is used for referring to a method in any object.

It can be further explained through the example mentioned below. It shows the lambda expression, which is used to call a single method that exists in the code. And throughout the entire execution, the lambda expression only calls the method.

list.forEach(s -> System.out.println(s));

In order to make the above line of code more readable, the lambda expression used in the above code is turned into the method reference.

list.forEach(System.out::println);

For the replacement of a single method only, method references are used. The code automatically turns short and becomes clearer when the user uses the lambda expression instead of using an anonymous class. Also, a user can use the method reference instead of using lambda expression for a single function. This will help the user achieve the same results. Also, the user doesn’t have to pass arguments while using the method references.

There are several types of a method reference in Java that are allowed in Java 8

  • Reference to some static methods: The static methods in a code can be referred to from a class.
  • Reference to some instance method of particular objects: Reference to some instance method of an arbitrary object of any particular type.
  • Reference to constructor

The article will discuss the various method references in Java.

1. Reference to some static methods

Using the reference to the static method, a static method present in a class can be referred to. The syntax of a method reference to static class is shown below.

ContainingClass::staticMethodName

2. Reference to Instance Method of a Particular Object

For understanding the concept of reference in this mentioned case, an example can be considered where there are two classes. 

Source 

An object of BicycleComparator can be created to compare the sizes of the frame of the bicycle.

Lambda expression could have been used to sort the bicycles through frame sizes. But for doing so, the two bikes need to be specified for comparison.

Source 

 In the line of code shown above, a method reference can be used so that the compiler could handle the parameter.

Source 

Using the method reference, the code becomes much more readable compared to the other cases. 

3. Reference to Instance Method of an Arbitrary Object of a Particular Type

In the above example, the reference to the instance method is used for a particular object. When the reference to the method of some arbitrary object is considered, it is almost similar to the above case. But, in this case, a custom object is not required to be created for performing the comparison. 

An example can be described below. An integer list that is required to be sorted can be created. 

Source 

If any lambda expression is used, then the parameters need to have been passed explicitly. But, if the user uses a method reference, the code becomes much more readable. It also becomes much more straightforward. 

Source

4. Reference to a constructor

This is another category of a method reference in Java, where  method reference can be created for a constructor. The reference can be made in a way that is similar to the ways mentioned in the earlier cases. There is a difference in creating a method reference for a constructor compared to the instance methods. In this case, the keyword “new” will be used. An example is discussed below to explain the method reference in the constructor. 

An array of bicycles is created from a list of string that consists of different brands. 

A new constructor is added at first to the class Bicycle. The code for adding the constructor to the Bicycle class is shown below. 

The constructor is now created. The created constructor is then used through a method reference for creating an array of Bicycles from the list of strings. 

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Conclusions

The different ways of method reference have been shown above with a few examples. We have come towards the end of the article and have seen how the method references in Java can be used for calling any existing method. Java has been a widely-used programming language in most developing applications around the world. It is a prerequisite to know the basics of Java if you are planning to enter into the world of application development and software.

Suppose you want to master your skills in this domain. In that case, you can check an online certification program in Software Engineering offered by upGrad. Designed for all working professionals, the course offers a 100% placement guarantee or money-back offer. More details of the course can be checked on the website. Also, for any assistance required, you can contact our team for help. 

What are the features that got updated in Java 8?

The features that got updated in Java 8 are Lambda expressions, Method reference, Functional inheritance, Stream API, etc.

What are lambda expressions?

These are anonymous functions that contain parameters, lambda, and a body of the function. These functions don’t have a name.

What do you mean by method reference?

It is the method where any method which is functionally important is referred to.

How does a method in method reference refer to?

For referring to a method in method reference, the name of the method is required.

Prepare for a Career of the Future

0 replies on “Method Reference in Java 8: Explained With Examples”

×
Let’s do it!
No, thanks.