Method References in Java

Method references in Java provide a concise way to refer to methods or constructors without invoking them. They can be seen as a shorthand notation for lambda expressions when the lambda expression only calls an existing method.

Method references can be used in functional interfaces, which are interfaces with a single abstract method. They allow you to pass behavior around as if it were a value. There are four different types of method references in Java:

Reference to a static method

You can refer to a static method using the class name followed by :: and the method name. For example, ClassName::methodName. This allows you to use an existing static method as a lambda expression.

Reference to an instance method of a particular object

You can refer to an instance method of a specific object using the instance name followed by :: and the method name. For example, instanceName::methodName. This allows you to use an existing instance method of an object as a lambda expression.

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

You can refer to an instance method of any object of a specific type using the class name followed by :: and the method name. For example, ClassName::methodName. This allows you to use an existing instance method as a lambda expression for objects of a specific type.

Reference to a constructor

You can refer to a constructor using the new keyword followed by :: and the class name. For example, ClassName::new. This allows you to use an existing constructor as a lambda expression to create new objects.

Example
import java.util.*; public class TestClass { public static void main(String[] args) { List weekDays = new ArrayList(); weekDays.add("Monday"); weekDays.add("Tuesday"); weekDays.add("Wednesday"); weekDays.add("Thursday"); weekDays.add("Friday"); weekDays.forEach(System.out::println); } } //Output: Monday Tuesday Wednesday Thursday Friday

Conclusion

Method references provide a more concise and readable syntax compared to lambda expressions in certain scenarios. They can improve code readability and reduce boilerplate code when working with functional interfaces. Method references are particularly useful when the lambda expression only calls an existing method without adding any additional logic.