The largest Interview Solution Library on the web


« Previous | 1 | 2 | 3 | Next »

Java_8 New - Method References


Method references helps to point to method by their name. A method reference is described using "::" symbol. A method referrence can be used to point 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;
publicclassJava8Tester{

publicstaticvoid main(String args[]){

List names =newArrayList();
names.add("Mahesh");
names.add("Suresh");
names.add("Ramesh");
names.add("Naresh");
names.add("Kalpesh");

names.forEach(System.out::println);
}
}

Here we've used 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 to see the result

C:\JAVA>java Java8Tester

See the result.

Mahesh
Suresh
Ramesh
Naresh
Kalpesh
« Previous | 1 | 2 | 3 | Next »


copyright © 2014 - all rights riserved by javatechnologycenter.com