A Block Lambda Expression is a lambda expression whose body contains multiple statements enclosed within curly braces {}. Unlike single-expression lambdas, block lambdas can include local variables, loops, conditional statements, and return statements, making them suitable for implementing more complex logic.
- A block lambda contains multiple statements enclosed within {}.
- Supports variables, loops, conditional statements, and nested blocks.
- Used when a lambda expression requires more than a single expression to perform its task.
@FunctionalInterface
interface Square {
int calculate(int n);
}
public class GFG {
public static void main(String[] args) {
Square square = (n) -> {
int result = n * n;
return result;
};
System.out.println(square.calculate(5));
}
}
Output
25
Syntax
(parameters) -> {
// multiple statements
}
Expression Lambda
Expression Lambda Expressions are lambda expressions whose body consists of a single expression without curly braces ({}). They are the simplest form of lambda expressions and are commonly used for short, concise operations.
- Contains only one expression in the lambda body.
- Curly braces {} and the return keyword are not required.
- The value of the expression is automatically returned (if the functional interface has a return type).
Syntax
(parameters) -> expression
interface Message {
void display();
}
public class Main {
public static void main(String[] args)
{
Message msg = ()
-> System.out.println(
"Welcome to GeeksforGeeks");
msg.display();
}
}
Output
Welcome to GeeksforGeeks
Features of Block Lambda Expressions
A block lambda expression can contain:
- Local variable declarations.
- Loops (for, while, do-while).
- Conditional statements (if, if-else, switch).
- Nested blocks.
- Method calls.
Demonstrate Block Lambda For Calculating Factorial
In this example, the lambda body contains multiple statements. It declares a local variable, uses a for loop to calculate the factorial, and returns the final result.
import java.io.*;
// Block lambda to find out factorial
// of a number
// Interface
interface Func {
// n is some natural number whose
// factorial is to be computed
int fact(int n);
}
class GFG {
// Main driver method
public static void main(String[] args)
{
// Block lambda expression
Func f = (n) ->
{
// Block body
// Initially initializing with 1
int res = 1;
// iterating from 1 to the current number
// to find factorial by multiplication
for (int i = 1; i <= n; i++)
res = i * res;
return res;
};
// Calling lambda function
// Print and display n the console
System.out.println("Factorial of 5 : " + f.fact(5));
}
}
Output
Factorial of 5: 120
Explanation:
- A local variable res is initialized to 1.
- The loop multiplies all numbers from 1 to 5.
- The computed factorial is returned by the lambda
Block Lambda to Check Leap Year
This block lambda uses an if-else statement to determine whether a given year is a leap year. Since multiple statements are involved, curly braces are required.
import java.io.*;
// Interface
// Functional interface named 'New'
interface New {
// Boolean function to check over
// natural number depicting calendar year
// 'n' deepicting year is
// passed as an parameter
boolean test(int n);
}
// Class
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// block lambda
// This block lambda checks if the
// given year is leap year or not
New leapyr = (year) ->
{
// Condition check
// If year is divisible by 400 or the
// year is divisible by 4 and 100 both
if (((year % 400 == 0)
|| (year % 4 == 0) && (year % 100 != 0)))
// Returning true as year is leap year
return true;
else
// Returning false for non-leap years
return false;
};
// Calling lambda function over
// custom input year- 2020
// Condition check using the test()
// defined in the above interface
if (leapyr.test(2020))
// Display message on the console
System.out.println("leap year");
else
// Display message on the console
System.out.println("Non leap year");
}
}
Output
leap year
Here in this block lambda has if-else conditions and return statements which are legal in lambda body.
Explanation:
- The lambda checks the leap year conditions.
- Since 2020 satisfies the leap year rules, it returns true.
- The program prints "leap year".
Expression Lambda vs Block Lambda
| Feature | Expression Lambda | Block Lambda |
|---|---|---|
| Body | Contains a single expression | Contains multiple statements enclosed in {} |
| Number of Statements | Single | Multiple |
Curly Braces {} | Optional | Mandatory |
return Statement | Not required (expression value is returned automatically) | Required when returning a value |
| Local Variables | Cannot declare local variables | Can declare and use local variables |
| Loops | Not supported | Supports for, while, and do-while loops |
| Conditional Statements | Limited to conditional expressions (?:) | Supports if, if-else, and switch statements |
| Complex Logic | Not suitable | Suitable for complex operations |
| Readability | Best for short, concise operations | Better for multi-step operations |
| Best Used For | Simple calculations or method calls | Business logic, validations, and multi-step computations |