Which of the following is a valid method reference in Java?
a) String::length
b) System.out::println
c) Math::max
d) All of the above
Answer:
d) All of the above
Explanation:
All of the provided examples are valid method references in Java. Each one refers to a method using the ::
syntax:
String::length
: Refers to thelength
instance method of theString
class.System.out::println
: Refers to theprintln
instance method of thePrintStream
class, often used for printing to the console.Math::max
: Refers to themax
static method of theMath
class, which returns the greater of two values.
Method references are a concise and readable way to refer to existing methods, making them a powerful tool when working with functional programming in Java. They reduce the need for boilerplate code and make the intent of your code more explicit, leading to cleaner and more maintainable applications.