In Java, a lambda expression can have two forms for its body:
Single Expression:A concise form where the body consists of a single expression. The result of this expression is implicitly returned.
Example:
java
(a, b) -> a + b
In this example, (a, b) are the parameters, and a + b is the single expression that adds them together.
Statement Block:A more detailed form where the body consists of a block of statements enclosed in braces {}. Within this block, you can have multiple statements, and if a return value is expected, you must explicitly use the return statement.
Example:
java
(a, b) -> {
int sum = a + b;
System.out.println("Sum is: " + sum);
return sum;
}
In this example, the lambda body is a statement block that performs multiple actions: it calculates the sum, prints it, and then returns the sum.
Given the options:
A. Two statements:While a lambda body can contain multiple statements, they must be enclosed within a statement block {}. Simply having two statements without braces is not valid syntax for a lambda expression.
B. An expression and a statement:Similar to option A, if a lambda body contains more than one element (be it expressions or statements), they need to be enclosed in a statement block.
C. A statement block:This is correct. A lambda expression can have a body that is a statement block, allowing multiple statements enclosed in braces.
D. None of the above:This is incorrect since option C is valid.
E. Two expressions:As with options A and B, multiple expressions must be enclosed in a statement block to form a valid lambda body.
Therefore, the correct answer is C: A statement block.