What is the syntax for a basic lambda expression in Java?
a) (parameters) -> expression
b) (expression) -> parameters
c) {expression} -> parameters
d) (parameters) => expression
Answer:
a) (parameters) -> expression
Explanation:
The basic syntax for a lambda expression in Java is (parameters) -> expression
. This syntax is straightforward: the parameters are enclosed in parentheses, followed by the arrow token (->), and then the expression or block of code. For example, a simple lambda expression that doubles a number can be written as:
(int x) -> x * 2
If the lambda expression contains more than one statement, curly braces {}
are required to enclose the block of code. For instance:
(int x) -> { int y = x * 2; return y; }
This flexibility allows lambda expressions to be used in various scenarios, making them a powerful feature in Java. Whether you’re performing simple operations or complex logic, lambda expressions offer a clean and concise way to define functionality on the fly.