Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Mastering Java 8: A Comprehensive Guide to 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 −

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

Java

  1. Java Methods: How to Define, Call, and Use Them Effectively
  2. Java Recursion: Understanding, Examples, and Trade‑Offs
  3. Mastering Method Overriding in Java
  4. Mastering Java Polymorphism: Concepts, Examples, and Best Practices
  5. Java Annotation Types: A Comprehensive Guide to Predefined, Custom, and Meta Annotations
  6. Mastering Java's Iterator Interface: Practical Guide with Code Example
  7. Understanding Java String.charAt(): Syntax, Return Type, Exceptions, and a Practical Example
  8. Mastering Java’s String.endsWith(): How to Check String Suffixes with Examples
  9. Mastering Java Methods: Create, Invoke, and Abstraction
  10. Java Method Overriding: Customizing Superclass Behavior