Java Method References: Static, Bound, Unbound and Constructor (OCP 21)
Method references for the OCP 21 exam: the :: operator, static, bound and unbound instance method references, constructor and array constructor references, how the target type picks overloads, this:: and super::, ambiguous references, and when a lambda can't be rewritten.
kvi5hnuCode Sprout team member6 min readOn this page
Many lambdas do nothing except pass their parameters on to an existing method:
interface Announcer { void announce(String msg); }
Announcer a1 = msg -> System.out.println(msg);
Announcer a2 = System.out::println; // the same thing, shorter
A method reference names the method to call and leaves out the parameter plumbing. The :: operator separates what to call it on (a class or an object) from the method name. Like a lambda, a method reference implements a functional interface and only runs when that interface's method is called. It's another way of writing a lambda, with the same deferred execution.
The four kinds

| Kind | Before :: | After :: | Example | Lambda equivalent |
|---|---|---|---|---|
| static method | class name | static method | Math::round | v -> Math.round(v) |
| instance method on a particular object (bound) | variable or expression | instance method | city::startsWith | p -> city.startsWith(p) |
| instance method on a parameter (unbound) | class name | instance method | String::isEmpty | s -> s.isEmpty() |
| constructor | class name | new | Badge::new | () -> new Badge() |
In every case, the target type (the functional interface) decides how many parameters there are and what they mean. You can't tell exactly what a method reference does without knowing its target.
1. Static methods
interface Rounder { long round(double value); }
Rounder r = Math::round; // like v -> Math.round(v)
System.out.println(r.round(4.5)); // 5
Math.round is overloaded: there's a round(double) that returns long and a round(float) that returns int. The compiler picks the overload that fits the target method, long round(double). If no overload fits, or more than one does, the reference doesn't compile.
2. Instance methods on a particular object (bound)
interface PrefixCheck { boolean startsWith(String prefix); }
String city = "Lisbon";
PrefixCheck p = city::startsWith; // like prefix -> city.startsWith(prefix)
System.out.println(p.startsWith("Lis")); // true
The object before :: is the receiver, and every parameter of the interface method becomes an argument. A bound reference can also call a method that takes nothing:
interface Check { boolean check(); }
String s = "";
Check c = s::isEmpty; // like () -> s.isEmpty()
this::method and super::method are bound references too. They can only be used where this exists, so not in a static context.
3. Instance methods on a parameter (unbound)
Here a class name comes before :: but the method is an instance method. The first parameter of the interface method becomes the object the method is called on, and any remaining parameters become its arguments:
interface Measure { int size(String text); }
interface TwoStrings { boolean test(String text, String prefix); }
Measure m = String::length; // like text -> text.length()
TwoStrings t = String::startsWith; // like (text, prefix) -> text.startsWith(prefix)
System.out.println(t.test("kiwi", "ki")); // true
String::startsWith looks like a call to a static method, but startsWith is an instance method, so Java uses the first parameter as the receiver. Parameter order matters: t.test("ki", "kiwi") would check whether "ki" starts with "kiwi", which is false.
4. Constructors
Class::new refers to a constructor. As with methods, the target type chooses which one:
interface Maker<T> { T make(); }
interface Builder<T> { T build(String arg); }
Maker<StringBuilder> empty = StringBuilder::new; // new StringBuilder()
Builder<StringBuilder> filled = StringBuilder::new; // new StringBuilder(String)
The same text, StringBuilder::new, calls two different constructors. If the class has no constructor that matches the target, compilation fails with "invalid constructor reference".
Arrays have constructor references too. int[]::new takes the length as its single parameter: an IntFunction<String[]> (article 50) built from String[]::new creates String arrays of a given size.
How the compiler matches a reference
For each reference, Java looks at the target method's parameters and return type, and searches for a method that fits any of the possible readings. Some consequences:
- Wrong shape: compile error.
Maker<Integer> m = String::length;fails becauselength()needs aStringto call it on, andmake()supplies none ("invalid method reference"). - Ambiguous: compile error. If you need an interface that maps an
Integerto aString,Integer::toStringmatches both the staticInteger.toString(int)and the instance methodtoString()called on the parameter. The compiler reports "reference to toString is ambiguous". Use a lambda instead. - Void targets accept results. As with lambdas, a target method returning
voidcan call a method that returns something. The result is discarded.
Not every lambda has a method reference
A method reference can only pass the interface's parameters straight through, in order. It can't add arguments of its own, rearrange the parameters, or do any extra work. So these lambdas have no method-reference form:
Check startsZ = () -> s.startsWith("Z"); // "Z" is an extra argument
s::startsWith("Z") // DOES NOT COMPILE: you can't pass arguments
Check c2 = s::startsWith; // DOES NOT COMPILE: startsWith needs an argument, check() has none
Every method reference can be rewritten as a lambda, but not the other way around.
Method references and variables
A bound reference evaluates its receiver expression immediately, when the reference is created, and keeps that object:
- The receiver variable doesn't need to be effectively final.
Maker<String> m = log::toString; log = other;compiles, andmkeeps using the original object. The lambda() -> log.toString()would not compile there, becauselogis reassigned. - If the receiver is
null, creating the reference throwsNullPointerExceptionright away. A lambda would only fail when called.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Method references can't use an unnamed
_parameter. That Java 22 feature applies only to lambdas (article 46).
Exam traps from this article
A complete example
Each kind of method reference sits next to its lambda twin. The program also uses one constructor reference for two different constructors, and shows that a bound reference keeps the object it captured.
import java.util.ArrayList;
import java.util.List;
public class Solution {
// Small functional interfaces, one per shape
interface Rounder { long round(double value); }
interface PrefixCheck { boolean startsWith(String prefix); }
interface TwoStrings { boolean test(String text, String prefix); }
interface Measure { int size(String text); }
interface Maker<T> { T make(); }
interface Builder<T> { T build(String arg); }
static class Badge {
private final String owner;
Badge() { this("guest"); }
Badge(String owner) { this.owner = owner; }
@Override public String toString() { return "Badge(" + owner + ")"; }
}
static String shout(String s) { return s.toUpperCase() + "!"; }
public static void main(String[] args) {
// 1. static method: Class::staticMethod
Rounder r1 = Math::round;
Rounder r2 = v -> Math.round(v);
System.out.println("static: " + r1.round(4.5) + " " + r2.round(4.49));
// 2. bound instance method: object::method (receiver fixed now)
String city = "Lisbon";
PrefixCheck p1 = city::startsWith;
PrefixCheck p2 = prefix -> city.startsWith(prefix);
System.out.println("bound: " + p1.startsWith("Lis") + " " + p2.startsWith("Rome"));
// 3. unbound instance method: Class::instanceMethod (first parameter is the receiver)
Measure m1 = String::length;
Measure m2 = text -> text.length();
TwoStrings t1 = String::startsWith;
TwoStrings t2 = (text, prefix) -> text.startsWith(prefix);
System.out.println("unbound: " + m1.size("harbor") + " " + m2.size("") + " "
+ t1.test("kiwi", "ki") + " " + t2.test("kiwi", "wi"));
// 4. constructor: Class::new (the target decides which constructor)
Maker<Badge> guest = Badge::new; // Badge()
Builder<Badge> named = Badge::new; // Badge(String)
Maker<List<String>> list = ArrayList::new;
System.out.println("constructor: " + guest.make() + " " + named.build("Ana") + " " + list.make());
// A static method of our own, used where a lambda would just forward the argument
Builder<String> loud = Solution::shout;
System.out.println("own static: " + loud.build("ready"));
// The receiver of a bound reference is evaluated once, when the reference is created
StringBuilder log = new StringBuilder("v1");
Maker<String> snapshot = log::toString;
log.append("+v2"); // same object: the change is visible
log = new StringBuilder("replaced"); // new object: the reference doesn't see it
System.out.println("bound receiver: " + snapshot.make() + ", variable now: " + log);
}
}
Output:
static: 5 4
bound: true false
unbound: 6 0 true false
constructor: Badge(guest) Badge(Ana) []
own static: READY!
bound receiver: v1+v2, variable now: replaced
Points to notice:
Math::roundpicksround(double)becauseRounder.roundtakes adouble.4.5rounds up to5.Badge::newcallsBadge()forMakerandBadge(String)forBuilder.String::startsWithused throughTwoStringstreats"kiwi"as the receiver and"ki"as the argument.Solution::shoutrefers to a static method of our own class.snapshotis bound to the firstStringBuilderobject, so it seesappendon that object but not the later reassignment oflog.
Common questions
Are method references faster than lambdas? Not meaningfully. Both are compiled to the same kind of run-time object. Choose whichever reads better.
When should I prefer a lambda? When you need extra arguments, a different parameter order, more than one call, or when the reference would be ambiguous.
Can a method reference refer to a generic or overloaded method? Yes. The compiler uses the target type to choose the overload and infer type arguments, and it fails only when that choice is impossible or ambiguous.
Summary
- A method reference
X::mis a shorthand for a lambda that only callsm, and it implements a functional interface. - Static (
Class::staticMethod): all parameters become arguments. Bound (obj::method): the object is fixed when the reference is created. Unbound (Class::instanceMethod): the first parameter is the receiver. - Constructor references (
Class::new,Type[]::new) choose a constructor based on the target's parameters. - The target type decides which overload is used. No match, or an ambiguous match, is a compile error.
- Method references can't add arguments or reorder parameters. Use a lambda then.
Practice quiz
Test yourself with the method references quiz: 10 exam-style questions with explanations.
Previous: Java Functional Interfaces: The Single Abstract Method Rule (OCP 21)
Next: Java Built-in Functional Interfaces: Supplier, Consumer, Predicate, Function and Operators (OCP 21)
Related reading
- Java Functional Interfaces: The Single Abstract Method Rule (OCP 21)
- Java Lambda Expressions: Syntax, Parameters and Bodies (OCP 21)
- Java Polymorphism: Reference Types, Casting and Virtual Method Calls (OCP 21)
- Java Local and Anonymous Classes (OCP 21)
- Java Nested Classes: Inner Classes and Static Nested Classes (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.