Java MCQ: What is the purpose of the method reference in Java 8?
Answer:
Explanation:
The purpose of a method reference in Java 8 is to enable functions (methods) to be passed as arguments in a lambda expression. Method references provide a shorthand, more readable syntax for writing lambdas that refer to existing methods. They are particularly useful when a lambda expression simply calls a method on a particular object or class.
There are four types of method references in Java:
- Reference to a static method:
ClassName::staticMethodName
- Reference to an instance method of a particular object:
object::instanceMethodName
- Reference to an instance method of an arbitrary object of a particular type:
ClassName::instanceMethodName
- Reference to a constructor:
ClassName::new
Here’s an example using a method reference to a static method:
import java.util.List;
public class MethodReferenceExample {
public static void main(String[] args) {
List<String> names = List.of("John", "Jane", "Jack", "Doe");
names.forEach(System.out::println);
}
}
In this example, System.out::println
is a method reference to the println
method of System.out
. It is passed as an argument to the forEach
method, which calls println
on each element of the names
list.
Method references make lambda expressions more concise and easier to read, promoting clean and maintainable code.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html