- Java 8 Tutorial
- Java 8 - Home
- Java 8 - Overview
- Java 8 - Environment Setup
- Java 8 - Lambda Expressions
- Java 8 - Method References
- Java 8 - Functional Interfaces
- Java 8 - Default Methods
- Java 8 - Streams
- Java 8 - Optional Class
- Java 8 - Nashorn JavaScript
- Java 8 - New Date/Time API
- Java 8 - Base64
- Java 8 Useful Resources
- Java 8 - Questions and Answers
- Java 8 - Quick Guide
- Java 8 - Useful Resources
- Java 8 - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java 8 - Method References
Method references help to point to methods by their names. A method reference is described using "::" symbol. A method reference can be used to point the following types of methods −
- Static methods
- Instance methods
- Constructors using new operator (TreeSet::new)
Method Reference Example
Create the following Java program using any editor of your choice in, say, C:\> JAVA.
Java8Tester.java
import java.util.List;
import java.util.ArrayList;
public class Java8Tester {
public static void main(String args[]) {
List names = new ArrayList();
names.add("Mahesh");
names.add("Suresh");
names.add("Ramesh");
names.add("Naresh");
names.add("Kalpesh");
names.forEach(System.out::println);
}
}
Here we have passed System.out::println method as a static method reference.
Verify the Result
Compile the class using javac compiler as follows −
C:\JAVA>javac Java8Tester.java
Now run the Java8Tester as follows −
C:\JAVA>java Java8Tester
It should produce the following output −
Mahesh Suresh Ramesh Naresh Kalpesh
Advertisements