Java8 Tutorial on 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