Skip to content
Tutorials Center
My learning

Topics

Lesson 100 of 201 ยท Generics and Functional Programming

Method References

Learn Java method references - static, bound and unbound instance, and constructor references, how they map to lambdas, when receivers are evaluated, and when a lambda reads better.

Many lambdas do nothing but call one existing method: s -> s.toUpperCase(), x -> IO.println(x), () -> new ArrayList<>(). A method reference names that method directly instead: String::toUpperCase, IO::println, ArrayList::new. The double colon :: says "use this method as the implementation of the functional interface".

Method references were added together with lambdas in Java 8, and they're everywhere in modern code, especially in streams and comparators: Comparator.comparing(Person::lastName) reads almost like English. This lesson explains the four kinds of method references, shows the lambda each one stands for, covers a subtle difference in when things are evaluated, and gives you guidelines for choosing between a method reference and a lambda. It assumes you know Lambda Expressions and Functional Interfaces.

The four kinds at a glance

Kind Syntax Example Equivalent lambda
Static method ClassName::staticMethod Integer::parseInt s -> Integer.parseInt(s)
Instance method of a particular object (bound) object::method prefix::concat s -> prefix.concat(s)
Instance method of an arbitrary object (unbound) ClassName::instanceMethod String::length s -> s.length()
Constructor ClassName::new StringBuilder::new () -> new StringBuilder()

Like a lambda, a method reference has no type of its own. The compiler looks at the target functional interface, works out which parameters it supplies, and checks that the named method can accept them and return a compatible result.

Static method references

ClassName::staticMethod passes the functional interface's parameters straight to a static method:

Java Static method references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The same reference adapts to different interfaces: Integer::parseInt works as a Function<String, Integer> (with boxing) and equally as a ToIntFunction<String>, and Math::max matches BinaryOperator<Integer> as well as IntBinaryOperator. When a method is overloaded, the compiler picks the overload that fits the target's parameter types; Math::max as an IntBinaryOperator selects max(int, int).

Integer::sum, Integer::compare, Math::abs, String::valueOf and Objects::nonNull are static helpers that exist largely so they can be used this way.

Bound instance method references

object::method calls a method on one specific object that you name in the reference. The functional interface's parameters become the method's arguments:

Java Bound references: a particular object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

System.out::println is the most famous bound reference: System.out is a particular PrintStream object, and the reference calls its println. Compare it with IO::println, which is a static method reference, because IO.println is a static method of the IO class (Java 25).

Inside instance methods you can also write this::method and super::method, which are bound to the current object:

Java
class Report {
    private String format(Row row) { ... }

    List<String> lines(List<Row> rows) {
        return rows.stream().map(this::format).toList();   // row -> this.format(row)
    }
}

When the receiver is evaluated

There's one behavioral difference between a bound reference and the lambda it seems to replace. In expr::method, the expression expr is evaluated once, when the reference is created. In the lambda x -> expr.method(x), it's evaluated every time the lambda runs:

Java The receiver is evaluated once, at creation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

After creating both suppliers, lookups is 1: only the reference called buffer(). The reference keeps returning first because it's bound to the object that existed when it was created, while the lambda follows currentBuffer to second. The same rule explains the null case: missing::length checks its receiver immediately and throws, while the lambda would fail only when called. Usually this difference doesn't matter, but it's worth knowing when the receiver is a method call or a field that changes.

Unbound instance method references

ClassName::instanceMethod names an instance method without naming the object. The object comes from the functional interface's first parameter, and any remaining parameters become the method's arguments:

  • String::toUpperCase as Function<String, String> means s -> s.toUpperCase().
  • String::compareToIgnoreCase as Comparator<String> means (a, b) -> a.compareToIgnoreCase(b).
  • String::startsWith as BiPredicate<String, String> means (s, prefix) -> s.startsWith(prefix).
Java Unbound references: the first parameter is the receiver

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Record accessors make perfect unbound references: Employee::team is a Function<Employee, String>, which is exactly what Comparator.comparing wants. Sorting with Comparable and Comparator builds whole sort orders this way.

To tell bound from unbound at a glance, look left of ::. A variable or expression (fiction, System.out, this) means bound: the object is fixed. A class name (String, Employee) with an instance method means unbound: each call brings its own object as the first argument.

Constructor references

ClassName::new refers to a constructor. The functional interface's parameters become constructor arguments, and the compiler picks the matching overload:

  • Supplier<ArrayList<String>>: ArrayList::new means () -> new ArrayList<>().
  • Function<Integer, ArrayList<String>>: the same ArrayList::new means n -> new ArrayList<>(n) (initial capacity).
  • BiFunction<String, Integer, Item>: Item::new means (name, qty) -> new Item(name, qty).

Array constructors work too: int[]::new is an IntFunction<int[]> meaning n -> new int[n]. That's what stream.toArray(String[]::new) uses, as you saw in Type Erasure and Generic Limitations.

Java Constructor and array constructor references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Constructor references shine as factories: a method that accepts Supplier<T> or Function<String, T> can create objects of whatever type the caller wants, which is how Collectors.toCollection(TreeSet::new) and Collectors.groupingBy(..., TreeMap::new, ...) let you choose the collection type (Collecting Stream Results).

Ambiguity and other compile errors

Sometimes the compiler can't decide what a reference means. The classic case is a method that exists both as a static method and as an instance method with compatible parameters:

Java
Function<Integer, String> f = Integer::toString;
// error: incompatible types: invalid method reference
//   reference to toString is ambiguous
//   both method toString(int) in Integer and method toString() in Integer match

Integer::toString could mean the static Integer.toString(int) (with the Integer unboxed) or the unbound instance method i.toString(). Fix it with a lambda, or with a reference that isn't ambiguous, such as String::valueOf or Object::toString.

Other errors you may meet:

  • "invalid method reference ... cannot be applied to given types": the method's parameters don't fit the target. Function<String, Integer> f = String::length; works, but BiFunction<String, String, Integer> g = String::length; doesn't, because length() takes no argument.
  • "invalid method reference ... unexpected instance method found in unbound lookup": you wrote ClassName::instanceMethod where the target doesn't provide an object as the first parameter, e.g. Supplier<Integer> s = String::length;. A supplier has no parameter that could become the string.

Method reference or lambda?

Method references are not automatically better. Use the one that reads more clearly:

Prefer a method reference Prefer a lambda
The lambda just forwards its parameters: x -> foo(x) โ†’ this::foo Arguments are rearranged or extra values added: x -> format(x, "EUR")
A well-named method says what happens: map(Order::total) The logic is short and clearer inline: filter(n -> n > 0)
Accessors and constructors: Person::name, Item::new The reference would be ambiguous or very long: SomeVeryLongUtilityClass::method
System.out::println, Integer::sum, Objects::nonNull You need the receiver evaluated on each call

A good habit: when a lambda grows beyond two or three lines, move the body into a named private method and pass a method reference to it. The stream pipeline then reads like a table of contents, and the logic gets a name and can be tested on its own.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which lambda is equivalent to String::trim used as a Function<String, String>?

    String::trim is an unbound instance method reference. The function's single parameter becomes the object on which trim() is called.
  2. 2. In Consumer<String> c = log::add;, where log is a List<String>, what kind of method reference is this?

    log is a particular object named left of ::, so the reference is bound to it and means s -> log.add(s).
  3. 3. What does BiFunction<String, Integer, Item> make = Item::new; select?

    For constructor references, the target's parameter types pick the constructor overload. Two parameters, String and Integer, select Item(String, int).
  4. 4. String s = null; Supplier<Integer> r = s::length; When is the NullPointerException thrown?

    The receiver of a bound method reference is evaluated and null-checked when the reference is created. The lambda () -> s.length() would fail only when called.
  5. 5. Why doesn't Function<Integer, String> f = Integer::toString; compile?

    Both interpretations fit Function<Integer, String>, so the compiler reports an ambiguous reference. Use String::valueOf or a lambda instead.

Summary

  • A method reference X::method replaces a lambda that only calls one existing method; its meaning comes from the target functional interface.
  • Four kinds: static (Integer::parseInt), bound instance (System.out::println, this::format), unbound instance (String::length, where the first parameter is the receiver), and constructor (ArrayList::new, int[]::new).
  • Overloaded methods and constructors are selected by the target's parameter types.
  • A bound reference evaluates its receiver once, at creation, and throws immediately if it's null; a lambda evaluates it on every call.
  • Ambiguous references (like Integer::toString as a Function<Integer, String>) don't compile; use a lambda or a different method.
  • Use method references when they name the action clearly; use lambdas when you rearrange arguments, add values or keep short logic inline.

Next: Streams, where filters, mappers and method references come together into readable data-processing pipelines.