In Java, method references provide a concise way to refer to methods or constructors without executing them. They are part of Java 8’s lambda expressions feature and are used mainly with functional interfaces. Method references make code shorter and more readable.
Syntax
There are four types of method references:
- Reference to a static method
ClassName::staticMethodName
- Reference to an instance method of a particular object
instance::instanceMethodName
- Reference to an instance method of an arbitrary object of a particular type
ClassName::instanceMethodName
- Reference to a constructor
ClassName::new
Examples
1. Static Method Reference
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] names = {"John", "Alice", "Bob"};
// Using method reference
Arrays.sort(names, String::compareToIgnoreCase);
for(String name : names) {
System.out.println(name);
}
}
}
- Here,
String::compareToIgnoreCase
refers to the static method for sorting.
2. Instance Method of a Particular Object
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
Consumer<String> printer = System.out::println;
printer.accept("Hello, World!");
}
}
System.out::println
refers to theprintln
method of theSystem.out
object.
3. Instance Method of an Arbitrary Object of a Particular Type
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] names = {"John", "Alice", "Bob"};
Arrays.sort(names, String::compareToIgnoreCase);
for(String name : names) {
System.out.println(name);
}
}
}
- This is similar to the static example, but it works on any object of a type.
4. Constructor Reference
import java.util.function.Supplier;
class Person {
String name;
Person() {
this.name = "Unknown";
}
}
public class Main {
public static void main(String[] args) {
Supplier<Person> personSupplier = Person::new;
Person person = personSupplier.get();
System.out.println(person.name); // Outputs "Unknown"
}
}
Person::new
refers to the constructor of thePerson
class.
✅ Key Points
- Method references are shorthand for lambda expressions.
- They improve code readability.
- They can only be used when the method signature matches the functional interface’s abstract method.