Skip to lesson

What is a method reference?

Your lambda does nothing except call a method that already exists, like s -> s.length(). It feels like too much typing for so little.

A lambda that only calls one method

A method reference, such as String::length, is a short way to write a lambda that only calls one existing method.

Many lambdas do one thing: they take their input and hand it straight to an existing method. s -> System.out.println(s) gives s to println. s -> s.length() calls length on s. text -> Integer.parseInt(text) gives text to parseInt.

Example 1 · The same task as a lambda and as a method reference

FirstReferenceDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.function.Consumer;import java.util.function.Function;
public class FirstReferenceDemo {    public static void main(String[] args) {        List<String> cities = new ArrayList<>(List.of("Pune", "Chennai", "Goa"));
        // printing every item: lambda, then method reference        cities.forEach(c -> System.out.println(c));        cities.forEach(System.out::println);
        // the same objects stored in variables        Consumer<String> printLambda = c -> System.out.println(c);        Consumer<String> printRef = System.out::println;        printLambda.accept("lambda says Delhi");        printRef.accept("reference says Delhi");
        Function<String, Integer> lengthLambda = c -> c.length();        Function<String, Integer> lengthRef = String::length;        System.out.println(lengthLambda.apply("Bengaluru") + " " + lengthRef.apply("Bengaluru"));    }}
Output
Pune
Chennai
Goa
Pune
Chennai
Goa
lambda says Delhi
reference says Delhi
9 9

What this code does

  • System.out::println and c -> System.out.println(c) build the same Consumer<String>. Each accept call runs println with the value it receives.
  • String::length is the short form of c -> c.length(). Both are a Function<String, Integer> and give 9 for "Bengaluru".

In these lambdas the parameter name carries no meaning. It is only a wire from the interface method to the real method. A method reference removes the wire. It is an expression with the :: symbol that names an existing method, such as System.out::println, and Java connects the arguments for you. A method reference creates exactly the same kind of object as the lambda: an object of a functional interface. It does not call the method when it is written. The method runs later, each time the interface method (accept, apply, test, get) is called.

Read :: as "use this method". String::length means "use the length method of String", not "call length now".

The four kinds at a glance

Every method reference has the form Something::name. What stands on the left of :: decides the kind, and each kind is a short form of one lambda shape.

Four kinds of method reference beside the lambda each replaces. Static: Integer::parseInt. Bound: System.out::println. Unbound: String::length. Constructor: ArrayList::new. What stands on the left of :: decides the kind.

Example 2 · All four kinds in one program

FourKindsDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.function.Consumer;import java.util.function.Function;import java.util.function.Supplier;
public class FourKindsDemo {    public static void main(String[] args) {        Function<String, Integer> parse = Integer::parseInt;
        Consumer<String> print = System.out::println;
        Function<String, String> shout = String::toUpperCase;
        Supplier<List<String>> newList = ArrayList::new;
        int marks = parse.apply("87") + 5;        print.accept("Marks after grace: " + marks);        print.accept(shout.apply("result declared"));
        List<String> toppers = newList.get();        toppers.add("Asha");        toppers.add("Ravi");        print.accept("Toppers: " + toppers);    }}
Output
Marks after grace: 92
RESULT DECLARED
Toppers: [Asha, Ravi]

What this code does

  • The left side of :: tells you the kind: a class with a static method, a fixed object, a class whose object comes in later, or new.
  • None of the four methods runs on the line where the reference is written. parseInt runs only inside parse.apply("87"), and the list is created only by newList.get().

The four kinds, each with the lambda it replaces:

  • Static method, ClassName::staticMethod: Integer::parseInt is s -> Integer.parseInt(s).
  • Bound instance method, object::method (the object is already known): System.out::println is x -> System.out.println(x).
  • Unbound instance method, ClassName::instanceMethod (the object comes in as the first argument): String::length is s -> s.length().
  • Constructor, ClassName::new: ArrayList::new is () -> new ArrayList<>().
The next four lessons in this module take one kind each, in this same order.

How the compiler matches a reference

A method reference has no type of its own. Java needs a target type: the functional interface that the place expects, such as the type of the variable or the parameter of forEach. Without a target type, String::length means nothing to the compiler.

  1. Find the target type: the functional interface the variable or parameter expects.
  2. Read its abstract method: how many inputs, of which types, and what it returns.
  3. Look at the left of :: to know the kind: a class, an object or new.
  4. Check that the named method takes those inputs in that order and returns a fitting value.

Example 3 · One reference, many target types

TargetTypeDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.function.BinaryOperator;import java.util.function.Function;import java.util.function.IntBinaryOperator;import java.util.function.ToIntFunction;
public class TargetTypeDemo {    public static void main(String[] args) {        Function<String, Integer> boxedLength = String::length;        ToIntFunction<String> plainLength = String::length;        System.out.println(boxedLength.apply("Kochi") + " " + plainLength.applyAsInt("Kochi"));
        BinaryOperator<Integer> higherBoxed = Math::max;        IntBinaryOperator higherPlain = Math::max;        System.out.println(higherBoxed.apply(72, 88) + " " + higherPlain.applyAsInt(72, 88));
        List<Integer> runs = new ArrayList<>(List.of(45, 12, 78, 30));        runs.sort(Integer::compare);        System.out.println(runs);    }}
Output
5 5
88 88
[12, 30, 45, 78]

What this code does

  • The same text String::length becomes a Function<String, Integer> in one line and a ToIntFunction<String> in the next. The target type decides which interface object is built.
  • Integer::compare takes two int values and returns an int, which is exactly the shape of Comparator<Integer>.compare, so sort accepts it.

Example 4 · Mistake: a method reference with no target type

NoTargetDemo.javaJava
import java.util.function.Function;
public class NoTargetDemo {    public static void main(String[] args) {        var length = String::length;        System.out.println(length);    }}
Sample compiler output
NoTargetDemo.java:5: error: cannot infer type for local variable length
        var length = String::length;
            ^
  (method reference needs an explicit target-type)
1 error

What this code does

  • var asks Java to take the type from the right side, but a method reference has no type of its own. Java has nothing to match String::length against, so it stops.
  • Fix: give the variable a functional interface type, Function<String, Integer> length = String::length;, or pass the reference straight to a method that expects one.

Java then reads the target's one abstract method and searches for a method that fits it. For Function<String, Integer> f = String::length; it reads Integer apply(String). The input is a String, so length is called on that String. length returns an int, and Java boxes it into the Integer that apply returns. The parameters must fit in number and in order, and the return value must fit the interface's return type. If the interface returns void, like Consumer, any return value is simply ignored. If nothing fits, or two methods fit equally well, the code does not compile.

Fix the error

Give the reference a target

Read the real compiler error, then pick the line that fixes it.

Round 1 of 2

A method reference needs an interface to turn into.

import java.util.function.*;
public class RefFix {
public static void main(String[] args) {
var len = String::length;
System.out.println(len.apply("Pune"));
}
}

Error

RefFix.java:5: error: cannot infer type for local variable len
        var len = String::length;
  (method reference needs an explicit target-type)

When a method reference is not possible

A method reference only replaces a lambda whose whole body is one method call that passes the lambda's parameters straight through, in the same order. Anything extra needs a lambda.

Java
Function<String, Integer> length = s -> s.length();  // one call, same argument...Function<String, Integer> length2 = String::length;  // ...so a reference worksPredicate<Integer> pass = m -> m >= 40;              // compares: no method to nameFunction<String, String> first3 = s -> s.substring(0, 3);      // fixed argumentFunction<String, String> clean = s -> s.trim().toUpperCase();  // two calls

m -> m >= 40 compares, so it has no method to name. s -> s.substring(0, 3) adds fixed arguments. s -> s.trim().toUpperCase() makes two calls. (a, b) -> b.compareTo(a) swaps the order. These stay lambdas, and that is perfectly fine.

When a lambda grows large, move its body into a well-named method and then refer to that method. Static method references come next.

Example 5 · Real use: cleaning an attendance list

AttendanceCleanDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class AttendanceCleanDemo {    public static void main(String[] args) {        // names typed by different class representatives        List<String> present = new ArrayList<>(List.of("  asha ", "RAVI", " meera", "  ", "john  "));
        present.replaceAll(String::trim);        present.removeIf(String::isEmpty);        present.replaceAll(String::toLowerCase);        present.sort(String::compareTo);
        System.out.println("Present today: " + present.size());        present.forEach(System.out::println);    }}
Output
Present today: 4
asha
john
meera
ravi

What this code does

  • replaceAll wants a UnaryOperator<String>, removeIf wants a Predicate<String> and sort wants a Comparator<String>. Each unbound reference fits because the list item becomes the object the method is called on.
  • Every lambda here would only have passed its parameter along, so each one reads better as a method reference: trim, drop empty entries, lower-case, sort, print.

Next step

Check your understanding

11 quick questions