Java Method References

Su Suriya Ravichandran Updated 18 Nov 2026
8 min read ·Lesson 170 of 306

What a Method Reference Is

A method reference is a shorthand for a lambda that does nothing except call one existing method. Instead of writing the lambda, you name the method with the :: operator:

s -> s.length()                 // lambda
String::length                  // method reference — same meaning

x -> System.out.println(x)      // lambda
System.out::println             // method reference

Like a lambda, a method reference has no type of its own; it becomes an instance of the functional interface expected by the context (its target type). The compiler checks that the referenced method's parameters and return type fit that interface's single abstract method.

Why use them: when a lambda only forwards its arguments to a method, the method reference is shorter and reads as a description of what is done (map(Enrollment::student) — "map each enrollment to its student") rather than how (map(e -> e.student())). It also encourages putting non-trivial logic in well-named methods instead of long lambdas.

The Four Kinds of Method Reference

KindSyntaxEquivalent lambdaExample
Static methodClassName::staticMethod(args) -> ClassName.staticMethod(args)Integer::parseInt
Instance method of a particular object (bound)object::method(args) -> object.method(args)System.out::println, prefix::concat
Instance method of an arbitrary object of a type (unbound)ClassName::instanceMethod(obj, args) -> obj.instanceMethod(args)String::length, String::startsWith
ConstructorClassName::new, Type[]::new(args) -> new ClassName(args)ArrayList::new, Course::new, String[]::new
import java.util.*;
import java.util.function.*;

public class Kinds {
    record Course(String code, int fee) { }

    static boolean isPremium(Course c) { return c.fee() >= 5000; }

    public static void main(String[] args) {
        Function<String, Integer> parse = Integer::parseInt;
        Predicate<Course> premium = Kinds::isPremium;

        String prefix = "GC-";
        Predicate<String> hasPrefix = prefix::equals;
        Function<String, String> addPrefix = prefix::concat;
        Consumer<Object> print = System.out::println;

        Function<String, Integer> length = String::length;
        BiFunction<String, String, Boolean> startsWith = String::startsWith;
        Function<Course, String> code = Course::code;

        Supplier<List<String>> newList = ArrayList::new;
        BiFunction<String, Integer, Course> makeCourse = Course::new;
        IntFunction<String[]> newArray = String[]::new;

        print.accept(parse.apply("42") + 1);
        print.accept(premium.test(new Course("DJ", 5999)));
        print.accept(hasPrefix.test("GC-") + " " + addPrefix.apply("1001"));
        print.accept(length.apply("Chennai") + " " + startsWith.apply("Coimbatore", "Coim"));
        Course c = makeCourse.apply("JAVA", 4999);
        print.accept(code.apply(c) + " " + c);
        List<String> list = newList.get();
        list.add("x");
        print.accept(list + " " + newArray.apply(3).length);
    }
}

Output:

43
true
true GC-1001
7 true
JAVA Course[code=JAVA, fee=4999]
[x] 3

1. Static method references

Integer::parseInt matches Function<String, Integer>: the function's argument is passed to parseInt. Kinds::isPremium refers to your own static method — a good way to give a condition a name and reuse it.

2. Bound instance method references — object::method

The object is fixed when the reference is created; the function's arguments become the method's arguments:

  • prefix::equals → s -> prefix.equals(s)
  • prefix::concat → s -> prefix.concat(s), giving "GC-1001"
  • System.out::println → x -> System.out.println(x), where System.out is the bound object

Inside a class, this::methodName and super::methodName refer to methods of the current object or its parent class.

3. Unbound instance method references — ClassName::instanceMethod

No object is fixed. The first argument of the function becomes the object the method is called on, and any remaining arguments are passed as parameters:

  • String::length → s -> s.length() (one argument: the receiver)
  • String::startsWith → (s, prefix) -> s.startsWith(prefix) (two arguments: receiver + parameter)
  • Course::code → c -> c.code() — the most common use, extracting a property

The syntax looks like a static reference, which is confusing at first. The rule: if the method is an instance method and no object is given, the object comes from the first argument.

4. Constructor references — ClassName::new

  • ArrayList::new as a Supplier<List<String>> calls the no-argument constructor.
  • Course::new as a BiFunction<String, Integer, Course> calls the record's two-argument constructor. Which constructor is used depends on the target type's parameters.
  • String[]::new as an IntFunction<String[]> creates an array of the given length — this is what stream.toArray(String[]::new) and list.toArray(String[]::new) use.

Method References versus Lambdas: Two Differences

Method references and lambdas aren't always exactly equivalent. Two behaviours matter in practice:

import java.util.function.*;

public class Bound {
    static class Counter {
        private final String name;
        private int value;
        Counter(String name) { this.name = name; }
        int next() { return ++value; }
        public String toString() { return name; }
    }

    public static void main(String[] args) {
        Counter current = new Counter("orders");
        Supplier<Integer> methodRef = current::next;
        Supplier<Integer> lambda = () -> current.next();
        System.out.println(methodRef.get() + " " + lambda.get() + " " + methodRef.get());

        Counter[] holder = {new Counter("first")};
        Supplier<String> boundOnce = holder[0]::toString;
        Supplier<String> evaluatedEachTime = () -> holder[0].toString();
        holder[0] = new Counter("second");
        System.out.println("method ref: " + boundOnce.get() + ", lambda: " + evaluatedEachTime.get());

        String missing = null;
        Supplier<Integer> lazy = () -> missing.length();
        System.out.println("lambda created fine");
        try {
            Supplier<Integer> eager = missing::length;
        } catch (NullPointerException e) {
            System.out.println("method ref on null receiver: NullPointerException at creation");
        }
    }
}

Output:

1 2 3
method ref: first, lambda: second
lambda created fine
method ref on null receiver: NullPointerException at creation
  1. Both call the same object's method when the receiver is a fixed variable: methodRef and lambda share current, so the counter goes 1, 2, 3.
  2. The receiver expression of a bound method reference is evaluated once, when the reference is created. holder[0]::toString captured the first counter; replacing holder[0] later doesn't affect it. The lambda evaluates holder[0] every time it runs, so it sees the second counter.
  3. A null receiver fails immediately for a method reference. missing::length throws NullPointerException at the moment the reference is created. The lambda () -> missing.length() is created without problems and would fail only when called.

When a Method Reference Doesn't Fit

Ambiguous references

import java.util.function.*;

public class Ambig {
    public static void main(String[] args) {
        Function<Integer, String> f = Integer::toString;
    }
}
Ambig.java:5: error: incompatible types: invalid method reference
        Function<Integer, String> f = Integer::toString;
                                      ^
    reference to toString is ambiguous
      both method toString(int) in Integer and method toString() in Integer match
1 error

Integer::toString could be the static Integer.toString(int) (the argument as parameter) or the instance method toString() (the argument as receiver). Both fit Function<Integer, String>, so the compiler refuses to guess. Use a lambda (i -> i.toString()) or a different method (String::valueOf).

When to keep a lambda

Use a lambda instead of a method reference when:

  • the call needs extra arguments or constants: s -> s.startsWith("GC-") (there's no method reference for "startsWith with this fixed argument");
  • the arguments are used in a different order or transformed: (a, b) -> b.compareTo(a);
  • more than one method is called: s -> s.strip().toLowerCase();
  • the lambda reads more clearly — x -> x * 2 is clearer than any method reference.

Practical Example: A Results Report Built from Method References

Stream pipelines are where method references are used most. This report parses enrollment data, keeps students who passed, summarises each course, and lists students who need support — with each kind of method reference doing a specific job.

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class Report {
    record Enrollment(String student, String course, int score) {
        static Enrollment parse(String line) {
            String[] f = line.split(",");
            return new Enrollment(f[0].strip(), f[1].strip(), Integer.parseInt(f[2].strip()));
        }
        boolean passed() { return score >= 50; }
    }

    record CourseSummary(String course, long students, double average, String topStudent) { }

    static class Formatter {
        private final int nameWidth;
        Formatter(int nameWidth) { this.nameWidth = nameWidth; }
        String line(CourseSummary s) {
            return String.format("%-" + nameWidth + "s %2d students  avg %5.1f  top %s",
                                 s.course(), s.students(), s.average(), s.topStudent());
        }
    }

    public static void main(String[] args) {
        String csv = """
            Asha, Java, 91
            Ravi, Java, 45
            Meena, Django, 77
            Kumar, Java, 68
            Asha, Django, 88
            Divya, Docker, 39
            """;

        List<Enrollment> all = csv.lines()
            .filter(Predicate.not(String::isBlank))
            .map(Enrollment::parse)
            .toList();

        Map<String, List<Enrollment>> byCourse = all.stream()
            .filter(Enrollment::passed)
            .collect(Collectors.groupingBy(Enrollment::course, TreeMap::new, Collectors.toList()));

        Formatter fmt = new Formatter(8);
        byCourse.entrySet().stream()
            .map(e -> new CourseSummary(
                e.getKey(),
                e.getValue().size(),
                e.getValue().stream().mapToInt(Enrollment::score).average().orElse(0),
                e.getValue().stream().max(Comparator.comparingInt(Enrollment::score)).map(Enrollment::student).orElse("-")))
            .map(fmt::line)
            .forEach(System.out::println);

        String[] failed = all.stream().filter(Predicate.not(Enrollment::passed)).map(Enrollment::student).toArray(String[]::new);
        System.out.println("needs support: " + String.join(", ", failed));

        Set<String> students = all.stream().map(Enrollment::student).collect(Collectors.toCollection(TreeSet::new));
        System.out.println("students: " + students);
    }
}

Output:

Django    2 students  avg  82.5  top Asha
Java      2 students  avg  79.5  top Asha
needs support: Ravi, Divya
students: [Asha, Divya, Kumar, Meena, Ravi]

Where each kind of reference appears:

ReferenceKindRole
String::isBlank, Enrollment::passed, Enrollment::course, Enrollment::score, Enrollment::studentUnbound instanceTest or extract something from each element
Enrollment::parseStaticTurn each text line into an Enrollment
fmt::line, System.out::printlnBound instanceUse a specific object — the formatter configured with a column width, and the console
TreeMap::new, TreeSet::new, String[]::newConstructorTell collectors and toArray which container to create

How the pipeline works:

  1. Parsing. csv.lines() splits the text block into lines; Predicate.not(String::isBlank) drops empty lines; the static factory Enrollment::parse converts each line.
  2. Grouping. Students who passed are grouped by course into a TreeMap (sorted keys). Divya's Docker enrollment failed, so Docker doesn't appear.
  3. Summarising. For each course, a lambda builds a CourseSummary — a lambda is the right choice here because it combines several values. Inside it, method references extract scores for the average and compare by score to find the top student.
  4. Formatting. fmt::line is a bound reference to a Formatter object that holds configuration (the column width). It's like System.out::println: a particular object whose method is called for each element.
  5. Arrays and sets. toArray(String[]::new) produces a typed String[]; toCollection(TreeSet::new) collects unique, sorted student names.

The result reads almost like a description of the report. That readability is the main reason to prefer method references wherever a lambda would only forward to an existing method.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Method References and get answers drawn from it.

Signed-in readers only.