Which of the following is a valid lambda expression in Java?
a) (x) -> x * 2
b) x -> return x * 2;
c) (x) -> {return x * 2;}
d) All of the above
Answer:
d) All of the above
Explanation:
All of the provided options are valid lambda expressions in Java. Each one defines a function that takes one argument and returns twice its value:
(x) -> x * 2
: A simple lambda expression with a single parameter and a single expression. The return keyword is implied.x -> return x * 2;
: A lambda expression without parentheses around a single parameter. The return keyword explicitly returns the result.(x) -> {return x * 2;}
: A lambda expression with a block of code. The curly braces are required when using multiple statements or the return keyword.
These variations showcase the flexibility of lambda expressions, allowing developers to choose the most suitable syntax based on the complexity of the logic. Whether you need a simple one-liner or a more complex operation, lambda expressions provide a versatile tool for writing cleaner, more maintainable code.