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.
Check out our free courses to get an edge over the competition.
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.
Check out upGrad’s Java Bootcamp
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:
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.
Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)
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.
Explore our Popular Software Engineering Courses
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.
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.
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.
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.
In the line of code shown above, a method reference can be used so that the compiler could handle the parameter.
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.
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.
upGrad’s Exclusive Software Development Webinar for you –
SAAS Business – What is So Different?
In-Demand Software Development Skills
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.
Explore Our Software Development Free Courses
|Blockchain Technology||React for Beginners||Core Java Basics|
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.
What is a method reference in Java?
To put it simply, a method is a collection of varied statements that bear the responsibility of performing specific tasks and returning the result to the caller. A method can also perform a specific task without returning anything. With the help of the method, you can reuse the code without the need to retyping the same. A method reference can be defined as a shorthand syntax of lambda expressions that are loaded with only one method call. A method reference is an alternative to creating an instance of a reference type. Among several other uses, method references can be used to create a functional interface instance (that is, an instance of a functional interface type). A functional interface is a type that has exactly one abstract method (it can have other methods, but it must have at least one). A functional interface type has a single abstract method declaration, which may be inherited from a supertype. Method references provide a safe way to refer to the methods of Java classes. The main purpose of method references is to reduce the number of redundant class names that appear in Java programs. This also eliminates naming conflicts when there are two different classes with the same internal name.
How Is Java 8 method reference different from lambda expression?
Java came up with a new feature called method reference in Java 8, which is basically a compact and easy form of the lambda expression. Java 8 method reference is used to refer method of functional interface. However, there is one slight difference between java method reference and lambda expression, which is that, while lambda expression is an anonymous method, that is a method without any name, designed specifically for the inline implementation of a method, java method reference is almost similar to Lambda expression, except it refers a method without executing it. There is yet another key difference between these two methods. Lambda expression makes use of the arrow operator to connect argument and functionality. Method reference in Java 8, on the other hand, uses the (::) operator to separate the method name from the name of an object or class.
Can we replace lambda expression with method reference?
Lambda expression and method reference are two different ways of writing anonymous function. Lambda expressions were introduced in Java 8. Although method reference is not a new concept, closures were already a native feature in Java. Method reference was introduced to remove the verbosity of closures in Java. Any method from java.lang.Function can be used as a method reference. It is not necessary to use new keyword while using method references. There is a performance advantage of using method reference over using lambda expressions. Although lambda expressions have been used quite extensively in functional-style programming, at times, they can be quite hard to understand. Therefore, to curb this challenge, replacing the same with method reference in java 8 can be a great way to simplify the process. However, it is important to consider that this is only applicable in cases when lambda expressions are used solely for the purpose of passing through one or more parameters. Replacing the pass-through lambda with method references in java 8 provides you with a variety of options for the way that the parameters are passed through. Furthermore, with the help of method references in Java 8, you can name the method to which you are passing the parameter.
What are some of the important features of Java 8?
Some of the most important features of Java 8 are mentioned below. forEach() method in Iterable Surface- This feature enables you to focus on business logic while writing code. Furthermore, with the help of this method, you can also keep the logic for iteration and business logic in separate places, which results in a higher separation of concern and cleaner code. Default And Static Methods In Interfaces- Java 8 allows interfaces to have both static and default methods. This means that you can quite easily use default and static keywords to create interfaces with method implementations. Lambda Expressions And Functional Interfaces- Java 8 recently introduced a new concept, named Functional Interfaces, with the help of which you can easily avoid any accidental addition of abstract methods in the functional interfaces. Furthermore, it also carries one major advantage: you can now use lambda expressions to instantiate an interface.
What are the new features in Java 8?
There are three new features included in Java 8: lambda expressions, method references, the Streams API. The first one, lambda expressions, is the most revolutionary feature. It changes the way we write code in Java and puts Java in line with most other programming languages. Method references and the stream API are additions to Java 8 that allow us to perform more advanced tasks than we could do before. 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.