What is method reference in Java?

What is method reference in Java?

a) A way to refer to methods of a class or object
b) A way to create a lambda expression
c) A way to call a method without arguments
d) A way to store a method in a variable

Answer:

a) A way to refer to methods of a class or object

Explanation:

A method reference in Java is a shorthand notation for a lambda expression that executes just one method. It is a way to refer to methods of a class or object directly, without invoking them. Method references make the code more readable and concise, especially when the lambda expression simply calls an existing method. Here is an example:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); names.forEach(System.out::println);

In this example, System.out::println is a method reference that refers to the println method of the System.out object. It is equivalent to the lambda expression x -> System.out.println(x), but is more concise.

Method references are a powerful feature in Java, enabling developers to write more concise and expressive code. They are particularly useful when working with the Stream API and other functional programming constructs, where method references can simplify the code and improve readability.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top