Home core java Method reference in Java 8 and double colon operator

Method reference in Java 8 and double colon operator

Before looking into what is method reference in java 8, let’s understand about java Double colon (::) operator, because to reference to a method always utilize double colon operator (::) .

The double colon operator (::) introduced in Java 8, the java double colon (::) operator, also known as method reference operator in Java, is used to call a method by referring to it with the help of its class directly. They behave exactly as the lambda expressions. The only difference it has from lambda expressions is that this uses direct reference to the method by name instead of providing a delegate to the method.

1. What is method reference in Java 8 ?

To create lambda expressions we use anonymous methods. Some times the implementation that you want to create in lambda is already available in existing method. In those cases method references enable you to refer functional interface method by name in place of lambda expressions.

Our specified method can be either static method or instance method. Functional interface method and our specified method should have same argument and compatible return types, except this remaining things like method name, modifiers are not required to match.

2. Various kinds of referencing a method :

  1. Reference to static method.
  2. Reference to an instance method of a particular object.
  3. Reference to an instance method of an arbitrary object of a particular type
  4. Reference to a Constructor

To define method reference we have to use :: (double colon) operator.

3. Reference to static method

You can refer to static method defined in the class. Following is the syntax and example which describe the process of referring static method in Java.

Syntax:

 <target class name>::<static method name>

3.1. Example with lambda expression :

@FunctionalInterface
interface MyFunctionalInterface {
    
    boolean isEvenNumber(int i);
}
 
public class MethodReferenceDemo {
 
    public static void main(String[] args) {
        //Lambda Example
        MyFunctionalInterface mi = i -> i%2 == 0;
        
        System.out.println(mi.isEvenNumber(15));//false
        System.out.println(mi.isEvenNumber(20));//true
    }
}

3.2. Same example with reference to a method :

@FunctionalInterface
interface MyFunctionalInterface {
    
    boolean isEvenNumber(int i);
}
 
public class MethodReferenceDemo {
    
    static boolean myImplementation(int i) {
        
        return i%2 == 0;
    }
 
    public static void main(String[] args) {
        
        MyFunctionalInterface mi = MethodReferenceDemo::myImplementation;
        
        System.out.println(mi.isEvenNumber(15));//false
        System.out.println(mi.isEvenNumber(20));//true
    }
}

4. Reference to an instance method

Like static methods, you can refer instance methods also. In the following example, we are describing the process of referring the instance method.

Syntax:

<target class object>::<instance method>

4.1. Reference to instance method example

@FunctionalInterface
interface MyFunctionalInterface {
 
    boolean isEvenNumber(int i);
}
 
public class MethodReferenceDemo {
    
    //instance method
    boolean myImplementation(int i) {
        
        return i%2 == 0;
    }
 
    public static void main(String[] args) {
        
        MethodReferenceDemo demo = new MethodReferenceDemo();
        MyFunctionalInterface mi = demo::myImplementation;
        
        MyFunctionalInterface mi2 = new MethodReferenceDemo()::myImplementation;
        
        System.out.println(mi.isEvenNumber(15));//false
        System.out.println(mi2.isEvenNumber(20));//true
    }
}

5. Reference to an instance method of an arbitrary object of a particular type

Like static methods, you can refer instance methods also. In the following example, we are describing the process of referring the instance method.

Syntax:

<arbitary object type>::<instance method>

Look into the example, String::toUpperCase, usually toUpperCase() method is called on a string reference but we have written class name “String” as like reference to static method.

In the following example, String is particular type and the arbitrary object is the instance of String that is used during method invoke. When reference to an instance method of an arbitrary object of a particular type, that invokes a method onto the current object.

5.1. Example 1

@FunctionalInterface
interface MyFunctionalInterface {
    
    String processString(String name);
}
 
public class MethodReferenceDemo {
    
    public static void main(String[] args) {
        
        MyFunctionalInterface f1 = s -> s.toUpperCase();
        System.out.println(f1.processString("Peter")); // PETER
    	
    	// Above two lines equalant to following lines
        MyFunctionalInterface f2 = String::toUpperCase;
        System.out.println(f2.processString("Peter")); // PETER
    }
}

5.2. Example 2

public class Student {

	private String name;
	private Integer id;

	public Student(String name) {
		this.name = name;
	}

	public String getUppercaseName() {
		return name.toUpperCase();
	}	
	
	public void printLowerCaseName() {
		System.out.println(name.toLowerCase());
	}
}
@FunctionalInterface
interface StudentFunctionalInterface {
    
    String getStudentName(Student student);
}
public class MethodReferenceArbitaryObjectDemo {
    
    public static void main(String[] args) {
        
    	StudentFunctionalInterface f = Student::getUppercaseName;
        System.out.println(f.getStudentName(new Student("Peter"))); // PETER
        
        final List<Student> students = Arrays.asList(
        		                              new Student("Mike"),
        		                              new Student("John"),
        		                              new Student("Martin")
        		                              );
        
        students.forEach(Student::printLowerCaseName);
    }
}

Output :

PETER
mike
john
martin

Conclusion

In this article we covered reference to various kinds of methods with examples. As constructors also special kind of methods, they execute at the time of object initialization, constructor reference also possible.

References

  1. Java documentation

Satish Varma
Satish Varmahttps://javabydeveloper.com
Satish is post graduated in master of computer applications and experienced software engineer with focus on Spring, JPA, REST, TDD and web development. Also founder of javabydeveloper.com. Follow him on LinkedIn or Twitter or Facebook

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay in Touch

Categories

Related Articles