What is a method reference in Java?
Why Interviewers Ask This
This tests whether you can apply Java knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
Answer
A method reference is a shorthand notation for a lambda expression that calls an existing method. Instead of x -> x.toUpperCase(), write String::toUpperCase. There are four kinds: static method reference (ClassName::staticMethod), instance method reference on a specific instance (instance::method), instance method reference on an arbitrary instance of a type (ClassName::instanceMethod), and constructor reference (ClassName::new). Method references are more readable than lambdas when the lambda just calls an existing method without any additional logic: list.forEach(System.out::println) vs list.forEach(x -> System.out.println(x)).
Common Mistake
Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real Java project.
More Java Questions
View all →- Intermediate What is the Java Collections Framework?
- Intermediate What is the difference between ArrayList and LinkedList?
- Intermediate What is HashMap in Java and how does it work internally?
- Intermediate What is the difference between HashMap and HashTable in Java?
- Intermediate What is the difference between HashMap and LinkedHashMap?