Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Method reference (::)

The :: syntax adapts an existing method, constructor, or array creation operation to a functional interface. It does not invoke the referenced operation immediately; the target type determines compatible parameters and the result.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

Type::staticMethod
expression::instanceMethod
Type::instanceMethod
ClassType::new
ArrayType::new
super::instanceMethod
TypeName.super::instanceMethod

An expression containing :: creates a method reference compatible with a target functional interface. A functional interface must define a single function contract, which multiple compatible abstract method declarations can express. Declarations matching public methods of Object are ignored when determining whether the interface is functional. The contract guides parameter and result compatibility and overload selection. The expression does not execute the referenced operation. var f = String::length is invalid because it supplies no target type.

Type::staticMethod references a static method. expression::instanceMethod binds a particular receiver, whereas Type::instanceMethod takes its receiver from the first argument of the later invocation. Thus, String::length fits ToIntFunction<String>: the String argument is the receiver, not a parameter of length().

ClassType::new references a constructor, and ArrayType::new creates an array of the supplied length. super::instanceMethod and TypeName.super::instanceMethod reference a supertype implementation where the language context permits. A reference can replace a lambda that forwards arguments to an existing operation.

Beware: in expression::instanceMethod, the receiver expression is evaluated and captured immediately; null causes NullPointerException then, rather than only upon invocation. In the example, Math::abs, String::length, and String[]::new execute only through the functional interfaces' methods.

Examples

import java.util.function.IntFunction;
import java.util.function.IntUnaryOperator;
import java.util.function.ToIntFunction;

public class Main {
    public static void main(String[] args) {
        IntUnaryOperator absolute = Math::abs;
        ToIntFunction<String> length = String::length;
        IntFunction<String[]> allocate = String[]::new;

        System.out.println(absolute.applyAsInt(-7));
        System.out.println(length.applyAsInt("Java"));
        System.out.println(allocate.apply(3).length);
    }
}

Result

7
4
3

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources