Can a lambda expression in Java have a body with multiple statements?
Answer:
Explanation:
A lambda expression in Java can indeed have a body with multiple statements, provided that the statements are enclosed in curly braces {}
. When a lambda expression contains more than one statement, it is treated like a regular method body. Here is an example:
(int x, int y) -> { int sum = x + y; System.out.println("Sum: " + sum); return sum; }
In this example, the lambda expression adds two integers, prints the sum, and returns the result. The use of curly braces allows for multiple operations to be performed within the lambda expression, making it versatile for more complex logic.
This capability makes lambda expressions a powerful tool for developers, allowing them to write more expressive and flexible code. Whether you’re performing simple calculations or complex data manipulations, lambda expressions provide the flexibility needed to implement a wide range of functionality in a concise manner.