Method Reference in Java (Instance, Static, and Constructor Reference)

  • 4.1/5
  • 5083
  • Jul 20, 2024

Method references are compact, easy-to-read lambda expressions for methods that already have a name.

Sometimes, a lambda expression does nothing but call an existing method. In those cases, it's often clearer to refer to the existing method by name.

There are four kinds of method references: bound, unbound, static, and constructor.

1) Bound Method References

A "bound method reference" refers to an instance method that's bound to a receiver object; its syntax is: containingObject::instanceMethodName.

2) Unbound Method References

An "unbound method reference" refers to an instance method that's not bound to a receiver object; its syntax is: ContainingType::methodName.

However, because an instance method still requires a receiver object, the receiver object is created by the JVM.

3) Constructor References

You can use a method reference to refer to a constructor without instantiating the named class; its syntax is: ClassName::new.

Constructor References with multiple parameters

For constructors with more than two parameters we need to create your own Functional Interfaces:

4) Static Method References

A "static method reference" refers to a static method in a specific class; its syntax is: ContainingClass::staticMethodName.

• • •

As needed, the same method reference or lambda can be assigned to different functional interfaces.

Index
Modern Java - What’s new in Java 9 to Java 17

32 min

What is differences between JDK, JVM and JRE ?

2 min

What is ClassLoader in Java ?

2 min

Object Oriented Programming (OOPs) Concept

17 min

Concurrency in Java: Creating and Starting a Thread

12 min

Concurrency in Java: Interrupting and Joining Threads

5 min

Concurrency in Java: Race condition, critical section, and atomic operations

13 min

Concurrency in Java: Reentrant, Read/Write and Stamped Locks

11 min

Concurrency in Java: "synchronized" and "volatile" keywords

10 min

Concurrency in Java: using wait(), notify() and notifyAll()

6 min

Concurrency in Java: What is "Semaphore" and its use?

2 min

Concurrency in Java: CompletableFuture and its use

18 min

Concurrency in Java: Producer-consumer problem using BlockingQueue

2 min

Concurrency in Java: Producer-Consumer Problem

2 min

Concurrency in Java: Thread pools, ExecutorService & Future

14 min

Java 8 Lambdas, Functional Interface & "static" and "default" methods

28 min

Method Reference in Java (Instance, Static, and Constructor Reference)

9 min

What’s new in Java 21: A Tour of its Most Exciting Features

14 min

Java Memory Leaks & Heap Dumps (Capturing & Analysis)

9 min

Memory footprint of the JVM (Heap & Non-Heap Memory)

15 min