Java 8 method reference example

In the Java 8 method reference example, i show you how to use a method from class or object using class::methodName type syntax. Method reference is a new feature called in Java 8 and is used to refer method of functional interface. In this tutorial, we are explaining method reference concept in detail.

Types of Method References

There are four types of method references in Java 8:

  • Reference to a static method.
  • Reference to an instance method of a particular object.
  • Reference to an instance method of an arbitrary object of a particular type.
  • Reference to a constructor.

1. Reference to static method: Used to refer static methods from a class

Let’s see example to use ClassName.isOdd() which is static method. Here, ClassName::isOdd equivalent to ClassName.isOdd(x).

It should produce the following output
Java 8 method reference example

2. Reference to instance method from instance: Refer to an instance method using a reference to the supplied object. We can use System.out::println to print the value. Since System.out is an instance of type PrintStream. Here, System.out::println equivalent to System.out.println(x)

It should produce the following output
Java 8 method reference example

3. Reference to instance method from class type: using the syntax Class::instanceMethodName, in this example we use String::compareTo equivalent to x.compareTo(y).

It should produce the following output
Java 8 method reference example

4. Reference to constructor: we use ArrayList::new equivalent to new ArrayList(), see detail in example below.

It should produce the following output
Java 8 method reference example

That’s all about Java 8 method reference example.

Reference
Method References

Download complete source code, click link below

Java-Method-Reference.zip (1 download)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons