Method References
Learn Java method references with static, bound, unbound, and constructor examples, plus overload ambiguity and equivalent lambdas.
Learn Java method references with static, bound, unbound, and constructor examples, plus overload ambiguity and equivalent lambdas.
Method References
A method reference lets a functional interface refer to an existing method or constructor. It can replace a lambda whose body only calls that member, as in s -> System.out.println(s) and System.out::println.
Introduction
Since Java 8, lambda expressions have let you pass behavior as data. When a lambda only delegates to an existing method, a method reference may express the same call more briefly: x -> System.out.println(x) can become System.out::println. Pick the form that makes the receiver and arguments easiest to follow; the shorter form is not always clearer.
Java has four method-reference forms. Static references (String::valueOf) name a class method. Bound instance references (System.out::println) capture a particular object. Unbound instance references (String::toUpperCase) take the receiver as the first argument. Constructor references (ArrayList::new) refer to a constructor. The functional-interface target supplies the parameter and return types; with overloaded methods, it can select one member or leave the reference ambiguous.
This post walks through all four types with examples and their equivalent lambdas. It also covers how the compiler infers types, why an unbound reference uses its first parameter as the receiver, and how constructor references match a functional interface’s parameter list. The examples include common mistakes, such as confusing bound with unbound references or trying to chain them (A::B::C).
See JLS §15.13 for the method-reference rules.
When to Use
- When the lambda body only forwards its inputs to one method
- In Stream operations where you pass method references as arguments (
list.forEach(System.out::println)) - When the method’s behavior and overload are clear, and the receiver and arguments are easy to identify
When Not to Use
- When the method call requires argument transformation or combination beyond the direct call
- When the method does something slightly different from what the functional interface expects
- When the method reference would be chained in a way that reduces readability
- When overload resolution is unclear or the reference hides which argument becomes the receiver; a lambda can make that choice explicit
Four Types of Method References
| Type | Syntax | Example | Equivalent Lambda |
|---|---|---|---|
| Static method | ClassName::methodName |
String::valueOf |
x -> String.valueOf(x) |
| Instance method of particular object | instance::methodName |
System.out::println |
x -> System.out.println(x) |
| Instance method of arbitrary object | ClassName::instanceMethodName |
String::toUpperCase |
x -> x.toUpperCase() |
| Constructor | ClassName::new |
ArrayList::new |
() -> new ArrayList() |
Method references and java.util.function have been available since Java 8. The runnable check below uses List.of() (Java 9+) and Stream.toList() (Java 16+):
import java.util.List;
import java.util.function.Function;
public class MethodReferenceCheck {
public static void main(String[] args) {
Function<String, Integer> length = String::length;
List<Integer> lengths = List.of("Java", "API").stream()
.map(length)
.toList();
System.out.println(lengths);
}
}
Expected output:
[4, 3]
Static Method References
// Lambda
Function<Integer, String> lambda = x -> String.valueOf(x);
// Method reference — cleaner
Function<Integer, String> ref = String::valueOf;
// Usage
String result = ref.apply(42); // "42"
// With streams
List<Integer> numbers = List.of(1, 2, 3);
numbers.stream()
.map(String::valueOf) // static method reference
.toList(); // ["1", "2", "3"]
Instance Method of a Particular Object
// Lambda
Consumer<String> lambda = s -> System.out.println(s);
// Method reference
Consumer<String> ref = System.out::println;
// Usage
ref.accept("Hello"); // prints "Hello"
// Another example — using a bounded instance
String prefix = "Result: ";
Function<String, String> concat = prefix::concat;
concat.apply("42"); // "Result: 42"
Instance Method of an Arbitrary Object (Unbound)
// Lambda
Predicate<String> lambda = s -> s.isEmpty();
// Method reference — the input string is the receiver of isEmpty()
Predicate<String> ref = String::isEmpty;
// Usage
ref.test(""); // true
ref.test("hi"); // false
// More examples
Function<String, String> upper = String::toUpperCase; // s -> s.toUpperCase()
Function<String, Integer> len = String::length; // s -> s.length()
BiPredicate<String, String> starts = String::startsWith; // (s, prefix) -> s.startsWith(prefix)
Constructor References
// Lambda
Supplier<ArrayList<String>> lambda = () -> new ArrayList<>();
// Method reference
Supplier<ArrayList<String>> ref = ArrayList::new;
// Usage
ArrayList<String> list = ref.get(); // new ArrayList<String>()
// With type parameters
Function<Integer, ArrayList<String>> sizedList = ArrayList::new; // capacity hint
ArrayList<String> list2 = sizedList.apply(10); // new ArrayList<String>(10)
Mermaid Diagram — Method Reference Types
flowchart TD
A["Method Reference Types"]
A --> B["Static Method\nClassName::method"]
A --> C["Bound Instance\ninstance::method"]
A --> D["Unbound Instance\nClassName::instanceMethod"]
A --> E["Constructor\nClassName::new"]
B --> F["String::valueOf\nx -> String.valueOf(x)"]
C --> G["System.out::println\nx -> System.out.println(x)"]
D --> H["String::toUpperCase\nx -> x.toUpperCase()"]
E --> I["ArrayList::new\n() -> new ArrayList()"]
Failure Scenarios
Reference to a method that doesn’t match the functional interface:
// BiFunction<String, String, Boolean> expects (String, String) -> Boolean
// String::startsWith is (String, String) -> boolean — it matches!
BiFunction<String, String, Boolean> startsWith = String::startsWith; // OK
// But what about:
Function<String, String> concat = String::concat; // OK — (String) -> String
// String::valueOf(Object) is static — can be used as Function<Object, String>
Function<Object, String> valueOf = String::valueOf; // OK
Chaining method references incorrectly:
// You cannot chain method references directly
// String::length::toString — INVALID
// You need a lambda for transformations
Function<String, Integer> len = s -> s.length();
Function<Integer, String> str = Object::toString; // boxed
// Or simply use the lambda form
Function<String, String> lenStr = s -> Integer.toString(s.length());
Constructor with no matching signature:
// ArrayList::new expects () -> ArrayList (Supplier)
// If you need a constructor with initial capacity:
Function<Integer, ArrayList<String>> withCapacity = ArrayList::new; // ArrayList(int)
ArrayList<String> list = withCapacity.apply(10); // new ArrayList<String>(10)
Ambiguous overloaded method reference:
String implements both CharSequence and Serializable, so neither overload below is more specific for a String argument:
import java.io.Serializable;
import java.util.function.Function;
class Formatter {
static String format(CharSequence value) { return "text: " + value; }
static String format(Serializable value) { return "serialized: " + value; }
// Compile-time error: the reference to format is ambiguous.
static Function<String, String> formatter = Formatter::format;
}
javac reports that the reference to format is ambiguous and names both overloads. A lambda can make the intended overload explicit:
Function<String, String> formatter =
value -> Formatter.format((CharSequence) value);
The cast selects format(CharSequence). If the method reference makes overload selection hard to see, use a lambda or a named wrapper that shows the choice.
Trade-off Table
| Approach | Pros | Cons |
|---|---|---|
| Method reference | Concise; names the delegated method | Receiver or overload may be less obvious |
| Lambda | Can make parameter flow explicit | More syntax for a direct call |
| Anonymous class | Can capture this, complex logic |
Very verbose |
| Named method | Reusable, documented | Requires a name and class association |
Code Snippets
Common method references in Stream:
List<String> names = List.of("alice", "bob", "charlie");
// Unbound instance method reference
names.stream()
.map(String::toUpperCase) // s -> s.toUpperCase()
.filter(String::isEmpty) // s -> s.isEmpty() — unlikely here but valid
.forEach(System.out::println); // s -> System.out.println(s)
// Static method reference
List<Integer> numbers = List.of(3, 1, 2);
numbers.stream()
.sorted(Integer::compare); // (a, b) -> Integer.compare(a, b)
// Constructor reference
Stream.generate(ArrayList::new) // () -> new ArrayList()
.limit(5)
.toList();
Comparator with method reference:
class Person {
private String name;
private int age;
// constructor, getters...
public static Comparator<Person> byName = Comparator.comparing(Person::getName);
public static Comparator<Person> byAge = Comparator.comparing(Person::getAge);
}
// Usage
List<Person> people = // ...
people.sort(Person.byName);
Observability Checklist
- Method reference target method actually exists and is accessible
- Functional interface signature matches the method reference’s calling convention
- Unbound instance method references (
String::length) match the single parameter of the target functional interface - Constructor references use a constructor that matches the functional interface’s abstract method signature
- Method reference chains do not attempt to chain directly — use a lambda for transformations
Quick Exercise: Bound and Unbound References
Given String text = "hello", translate each reference to a lambda and identify the receiver:
- Bound:
text::contains - Unbound:
String::contains, targeted as aBiPredicate<String, String>
Answers: text::contains becomes part -> text.contains(part); text is the fixed receiver. String::contains becomes (receiver, part) -> receiver.contains(part); the first argument is the receiver.
Security Notes
- Method references carry the same security considerations as lambdas
- References to static methods on security-sensitive classes should be reviewed — they can escape the intended call path
- Constructor references (
ClassName::new) bypass normal construction controls — ensure the referenced constructor is appropriate for the use case (e.g., not exposing internals via a public constructor meant for internal use)
Pitfalls
- Confusing unbound instance method references with bound ones —
String::toUpperCaseis unbound (input is the receiver);System.out::printlnis bound (the instance is fixed) - Trying to chain method references —
A::B::Cis invalid — use a lambda for multi-step transformations - Generic type inference failures — sometimes
SomeClass::<String>methodsyntax is needed to clarify type parameters - Ambiguous overload resolution — when a class has multiple overloaded methods, the compiler may not be able to determine which to use
- Overusing method references — when the lambda body does more than just call a method, a full lambda is clearer
Quick Recap
- Method reference syntax:
ClassName::methodNameorinstance::methodName - Four types: static methods, bound instance methods, unbound instance methods, constructor references
- Unbound instance method references bind the first parameter as the receiver of the method call
- Use a method reference when it makes a direct call easier to read; use a lambda when it makes parameter flow or overload selection clearer
- Constructor references (
ClassName::new) are the way to pass construction as a first-class value
Interview Questions
- or similar based on what the context needs, using the diamond-inferred types to resolve which constructor is appropriate."
Further Reading
- Lambda Expressions — lambda syntax, functional interfaces, and variable capture
- Variable Scope — effectively final and closure behavior
- Static Methods — static method references and class-level operations
- Stream API Documentation — method references in stream operations
- java.util.function Package — functional interfaces that method references implement
Conclusion
Method references can shorten lambdas that directly call an existing method. For example, String::valueOf can stand in for x -> String.valueOf(x) when the target type makes the overload clear. Java has four forms: static methods (ClassName::staticMethod), bound instances (instance::method), unbound instance methods (ClassName::instanceMethod, where the first parameter becomes the receiver), and constructors (ClassName::new).
The key distinction between bound and unbound instance method references: a bound reference has a fixed receiver (System.out::println), making it a Consumer<String>; an unbound reference treats the first argument as the receiver (String::toUpperCase), making it a Function<String, String>. Constructor references (ArrayList::new) implement Supplier or Function depending on the constructor signature.
For a direct call, either form can work. Use a method reference when its receiver and target overload are obvious; use a lambda when parameter flow, argument changes, or overload choice need to be spelled out. Both forms appear often in Stream operations (map(String::toUpperCase), sorted(Integer::compare)) and comparator definitions.
For how lambdas and method references relate to each other, see Lambda Expressions. For the broader functional programming context and variable capture rules, see Variable Scope.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.