Static method references
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A static method reference like Integer::parseInt or Math::max points to a static method through its class name. It replaces a lambda that passes all its inputs straight into that one static method.
ClassName::staticMethod
Static method reference is written ClassName::method and names a static method, such as Math::max. The inputs of the interface are passed to that method in order, and its result becomes the interface result.
A static method reference names a static method through its class: Integer::parseInt, Math::max, String::valueOf. It is the short form of a lambda that passes all its parameters into that static method, in the same order.
Example 1 · Built-in static references: parseInt, max, valueOf and sum
import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.function.BinaryOperator;import java.util.function.Function;
public class BuiltInStaticDemo { public static void main(String[] args) { Function<String, Integer> toNumber = Integer::parseInt; BinaryOperator<Integer> better = Math::max; Function<Integer, String> toText = String::valueOf;
// two attempts of a test, typed into a form as text int first = toNumber.apply("68"); int second = toNumber.apply("81"); int best = better.apply(first, second); String label = toText.apply(best); System.out.println("Best attempt: " + label + " (" + label.length() + " characters)");
// total marks per subject with Map.merge and Integer::sum Map<String, Integer> totals = new TreeMap<>(); List<String> entries = List.of("Maths:40", "Physics:35", "Maths:45", "Physics:38"); for (String e : entries) { String[] parts = e.split(":"); totals.merge(parts[0], toNumber.apply(parts[1]), Integer::sum); } System.out.println(totals); }}Best attempt: 81 (2 characters)
{Maths=85, Physics=73}What this code does
Integer::parseInt,Math::maxandString::valueOfreplaces -> Integer.parseInt(s),(a, b) -> Math.max(a, b)andn -> String.valueOf(n). Each passes every input straight into the static method.Map.mergewants aBiFunctionthat combines the old and the new value.Integer::sumis the static methodsum(int a, int b), soMathsbecomes 40 + 45 = 85.
So Integer::parseInt is s -> Integer.parseInt(s), and Math::max is (a, b) -> Math.max(a, b). No object is involved, because a static method belongs to the class, not to any one object. The old way was an anonymous class with a full apply method around one line. The lambda shortened that to one line. The method reference goes one step further and keeps only the part that matters: which method does the work.
(a, b) -> Math.max(b, a), or adds a value, like x -> Math.max(x, 0), it cannot become a reference.Your own utility methods
Static references are not only for the Java library. Any static method you write can be referenced, as long as its parameters and return type fit the interface.
Example 2 · Your own utility: GradeUtils::gradeFor
import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.function.Function;
class GradeUtils { private GradeUtils() { }
static String gradeFor(int marks) { if (marks >= 90) { return "A+"; } else if (marks >= 75) { return "A"; } else if (marks >= 60) { return "B"; } else if (marks >= 40) { return "C"; } return "F"; }
static boolean isFail(int marks) { return marks < 40; }}
public class GradeReportDemo { static void printReport(Map<String, Integer> marks, Function<Integer, String> grader) { marks.forEach((name, m) -> System.out.println(name + " " + m + " -> " + grader.apply(m))); }
public static void main(String[] args) { Map<String, Integer> marks = new LinkedHashMap<>(); marks.put("Asha", 93); marks.put("Ravi", 67); marks.put("Meera", 38); marks.put("John", 76);
printReport(marks, GradeUtils::gradeFor);
List<Integer> scores = new ArrayList<>(marks.values()); scores.removeIf(GradeUtils::isFail); System.out.println("Passed scores: " + scores); }}Asha 93 -> A+ Ravi 67 -> B Meera 38 -> F John 76 -> A Passed scores: [93, 67, 76]
What this code does
printReportaccepts anyFunction<Integer, String>, andGradeUtils::gradeForfits: oneintin (unboxed fromInteger), aStringout. The grading rule has a name and lives in one place.removeIfwants aPredicate<Integer>.GradeUtils::isFailtakes anintand returns aboolean, so it fits too. A five-line lambda insideprintReportwould have been much harder to read.
This is the clean way to handle a long lambda. Move the rule into a static method with a clear name, such as GradeUtils.gradeFor(int marks), then pass GradeUtils::gradeFor. The rule now has a name, can be tested on its own and is reused everywhere. A utility class is a class that only holds static helper methods, like Math or your own GradeUtils. It usually has a private constructor so nobody creates objects of it.
Matching parameters to the interface
The interface's abstract method decides which static methods fit. Java passes the interface's inputs into the static method one by one, in order, and uses its result as the interface's result.
Example 3 · One static method, three interfaces
import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.function.BiFunction;import java.util.function.BinaryOperator;import java.util.function.Consumer;
class TextRules { // shorter names first; same length in A to Z order static int compareByLength(String a, String b) { if (a.length() != b.length()) { return Integer.compare(a.length(), b.length()); } return a.compareTo(b); }
static String longer(String a, String b) { return a.length() >= b.length() ? a : b; }}
public class MatchingDemo { public static void main(String[] args) { Comparator<String> byLength = TextRules::compareByLength; BiFunction<String, String, Integer> sameAsFunction = TextRules::compareByLength; BinaryOperator<String> pickLonger = TextRules::longer;
List<String> cities = new ArrayList<>(List.of("Surat", "Pune", "Kolkata", "Agra", "Indore")); cities.sort(byLength); System.out.println(cities); System.out.println(sameAsFunction.apply("Goa", "Delhi")); System.out.println(pickLonger.apply("Mysuru", "Ooty"));
// a void interface ignores the int that parseInt returns Consumer<String> mustBeNumber = Integer::parseInt; mustBeNumber.accept("2024"); System.out.println("2024 is a valid number"); }}[Agra, Pune, Surat, Indore, Kolkata] -1 Mysuru 2024 is a valid number
What this code does
compareByLengthtakes twoStringvalues and returns anint. That shape matchesComparator<String>and alsoBiFunction<String, String, Integer>, where theintis boxed toInteger.BinaryOperator<String>needs twoStringinputs and aStringresult, whichlongergives.Consumerreturns nothing, soInteger::parseIntis allowed there and its result is dropped; it still throws if the text is not a number.
Function<T, R>: one input, one result.Integer::parseIntasFunction<String, Integer>.BinaryOperator<T>: two inputs of type T, result of type T.Math::maxorInteger::sumasBinaryOperator<Integer>.Comparator<T>: two inputs of type T, anintresult.Integer::compareasComparator<Integer>.Predicate<T>: one input, abooleanresult.Character::isDigitasPredicate<Character>.
One method can fit several interfaces when their shapes agree. static int compareByLength(String a, String b) fits Comparator<String> (two inputs, int out) and also BiFunction<String, String, Integer>. If the interface returns void, such as Consumer, the method's return value is thrown away.
Trap: overloaded methods make a reference ambiguous
An overloaded method has several versions with the same name and different parameters. A lambda calls one version directly. A method reference only gives the name, so Java must pick the version itself, and sometimes two fit equally well.
Example 4 · Trap: Integer::toString is ambiguous
import java.util.function.Function;
public class AmbiguousDemo { public static void main(String[] args) { Function<Integer, String> asText = Integer::toString; System.out.println(asText.apply(42)); }}AmbiguousDemo.java:5: error: incompatible types: invalid method reference
Function<Integer, String> asText = Integer::toString;
^
reference to toString is ambiguous
both method toString(int) in Integer and method toString() in Integer match
1 errorWhat this code does
Integerhas a statictoString(int)and an instancetoString(). With anIntegerinput, Java could callInteger.toString(x)orx.toString(). Both fit, so neither is chosen.- The reference names a method but not which version. A lambda such as
x -> Integer.toString(x)names the exact call, so it has no such problem.
Example 5 · Fixing ambiguous references
import java.util.function.Function;import java.util.function.ToIntFunction;
public class AmbiguityFixDemo { static void convert(Function<String, Integer> f) { System.out.println("Function: " + f.apply("42")); }
static void convert(ToIntFunction<String> f) { System.out.println("ToIntFunction: " + f.applyAsInt("42")); }
static int digitsOnly(String s) { return Integer.parseInt(s.trim()); }
public static void main(String[] args) { // Integer::toString is ambiguous; these three are not Function<Integer, String> a = x -> Integer.toString(x); Function<Integer, String> b = String::valueOf; Function<Integer, String> c = Object::toString; System.out.println(a.apply(7) + b.apply(8) + c.apply(9));
// convert(Integer::parseInt) is ambiguous; these two are not convert((ToIntFunction<String>) Integer::parseInt); convert(AmbiguityFixDemo::digitsOnly); }}789 ToIntFunction: 42 ToIntFunction: 42
What this code does
- For
Integer::toString, use a lambda that names the call,String::valueOf, orObject::toString, which has only the one instance version. convert(Integer::parseInt)fails with "reference to convert is ambiguous" becauseparseInthas several versions. A cast picks the interface. A helper with one version, likedigitsOnly, lets Java choose on its own: anintresult fitsToIntFunctionbest.
The classic case is Function<Integer, String> f = Integer::toString;. Java finds the static toString(int) and the instance toString(), which could also run on the Integer argument. Both fit, so the compiler stops with "reference to toString is ambiguous". A second case: you pass Integer::parseInt, which has several versions, to a method that is itself overloaded, for example convert(Function) and convert(ToIntFunction). Java cannot use an overloaded reference to choose between them. Fix both cases with a lambda, a cast such as (ToIntFunction<String>) Integer::parseInt, or a helper method that has only one version.
Fix the error
Fix the ambiguous reference
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
Integer has two methods named toString. Make the choice clear.
Error
StaticFix.java:5: error: incompatible types: invalid method reference
Function<Integer, String> text = Integer::toString;
reference to toString is ambiguous
both method toString(int) in Integer and method toString() in Integer matchNext step
Check your understanding
11 quick questions