Which symbol is used to define a method reference in Java?
Answer:
Explanation:
The ::
symbol is used to define a method reference in Java. This symbol allows you to refer to methods by their names, making it easier to pass methods as arguments to functional interfaces. Method references can refer to static methods, instance methods, or constructors. Here is an example of a static method reference:
Function<String, Integer> parseInt = Integer::parseInt; int number = parseInt.apply("123"); // number is 123
In this example, the Integer::parseInt
method reference refers to the parseInt
static method of the Integer
class, which converts a string to an integer.
Method references are a concise and powerful way to work with functional interfaces, making your code more readable and maintainable. They are especially useful when the lambda expression would otherwise only call an existing method, allowing you to eliminate unnecessary code.