Java Name an Existing Operation Directly
A method reference can express that an existing method is the operation you want to pass. Use it when it makes the relationship clearer than repeating a small lambda.
Understand the idea
Static methods, instance methods and constructors have different method-reference forms. A target functional interface still determines the required signature. A bound reference such as object::method captures a particular receiver; Type::instanceMethod leaves the receiver to a compatible argument. Method references do not bypass null, accessibility or exception rules.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<String, String> clean = String::strip;
Function<String, StringBuilder> builder = StringBuilder::new;
System.out.println(clean.apply(" Clay "));
System.out.println(builder.apply("Wood").append(" lab"));
}
}
Expected output
Clay
Wood labString::strip is compatible with a function receiving a String and returning a String. The constructor reference creates a builder from its supplied text. Neither declaration executes the operation until apply is called. If the mapping involved extra validation or several decisions, a named helper method would often be clearer.
Check the official Java documentation for detailed contracts and supported options.