«Back to Home

Core Java

Topics

Method References In Java

Method References
 
Method references are introduced in Java 8. Method references help to identify methods by their names and it is expressed using :: (double colon) symbol.
 
A method reference is used to identify the following types of methods.
  • Static methods

  • Instance methods

  • Constructors using new operator
Let’s see an example of Method Reference.
 
Code
  1. import java.util.List;  
  2. import java.util.ArrayList;  
  3. public class MethodReferencesExample {  
  4.     public static void main(String args[]) {  
  5.         List l = new ArrayList();  
  6.         l.add("Jack");  
  7.         l.add("Bob");  
  8.         l.add("Harry");  
  9.         l.add("Mia");  
  10.         l.forEach(System.out::println);  
  11.     }  
  12. }  
14

Output

15

In the above example, we pass System.out::println method as a static method reference.
 
Summary

Thus, we learned that Method references help to identify methods by their names and also learns how to use it in Java.