Skip to lesson

Static method references

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

BuiltInStaticDemo.javaJava
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);    }}
Output
Best attempt: 81 (2 characters)
{Maths=85, Physics=73}

What this code does

  • Integer::parseInt, Math::max and String::valueOf replace s -> Integer.parseInt(s), (a, b) -> Math.max(a, b) and n -> String.valueOf(n). Each passes every input straight into the static method.
  • Map.merge wants a BiFunction that combines the old and the new value. Integer::sum is the static method sum(int a, int b), so Maths becomes 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.

If the lambda changes the order, like (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

GradeReportDemo.javaJava
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);    }}
Output
Asha 93 -> A+
Ravi 67 -> B
Meera 38 -> F
John 76 -> A
Passed scores: [93, 67, 76]

What this code does

  • printReport accepts any Function<Integer, String>, and GradeUtils::gradeFor fits: one int in (unboxed from Integer), a String out. The grading rule has a name and lives in one place.
  • removeIf wants a Predicate<Integer>. GradeUtils::isFail takes an int and returns a boolean, so it fits too. A five-line lambda inside printReport would 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

MatchingDemo.javaJava
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");    }}
Output
[Agra, Pune, Surat, Indore, Kolkata]
-1
Mysuru
2024 is a valid number

What this code does

  • compareByLength takes two String values and returns an int. That shape matches Comparator<String> and also BiFunction<String, String, Integer>, where the int is boxed to Integer.
  • BinaryOperator<String> needs two String inputs and a String result, which longer gives. Consumer returns nothing, so Integer::parseInt is 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::parseInt as Function<String, Integer>.
  • BinaryOperator<T>: two inputs of type T, result of type T. Math::max or Integer::sum as BinaryOperator<Integer>.
  • Comparator<T>: two inputs of type T, an int result. Integer::compare as Comparator<Integer>.
  • Predicate<T>: one input, a boolean result. Character::isDigit as Predicate<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

AmbiguousDemo.javaJava
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));    }}
Sample compiler output
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 error

What this code does

  • Integer has a static toString(int) and an instance toString(). With an Integer input, Java could call Integer.toString(x) or x.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

AmbiguityFixDemo.javaJava
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);    }}
Output
789
ToIntFunction: 42
ToIntFunction: 42

What this code does

  • For Integer::toString, use a lambda that names the call, String::valueOf, or Object::toString, which has only the one instance version.
  • convert(Integer::parseInt) fails with "reference to convert is ambiguous" because parseInt has several versions. A cast picks the interface. A helper with one version, like digitsOnly, lets Java choose on its own: an int result fits ToIntFunction best.

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.

import java.util.function.Function;
public class StaticFix {
public static void main(String[] args) {
Function<Integer, String> text = Integer::toString;
System.out.println(text.apply(42));
}
}

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 match

Next step

Check your understanding

11 quick questions