Course contentsShow
← Java
Lesson 1704 of 2,87036. Lambda Expressions and Method ReferencesFree lesson

Block Body: Multiple Statements with Braces

Write lambda expressions with multiple statements enclosed in curly braces forming a block body.

Block Body: Multiple Statements with Braces

You'll learn how to write lambda expressions that execute multiple statements by wrapping them in curly braces.

The Core Idea

So far, you've seen expression-body lambdas where a single expression automatically returns a value. But what if your lambda needs to do more than one thing? That's where the block body comes in.

When your lambda requires multiple statements—perhaps validation, logging, calculation, and then returning a result—you enclose those statements in curly braces {}, just like a regular method body. This transforms your lambda from an expression into a full code block.

How Block Bodies Work

With a block body, you must explicitly use the return keyword if your functional interface expects a return value. The compiler no longer treats the result as implicit.

Expression body (single statement):

Function<Integer, Integer> square = x -> x * x;

Block body (multiple statements):

Function<Integer, Integer> squareWithLog = x -> {
    System.out.println("Squaring: " + x);
    int result = x * x;
    return result;
};

Notice the braces, multiple statements, and explicit return.

Practical Example

Consumer<String> processName = name -> {
    String trimmed = name.trim();
    String upper = trimmed.toUpperCase();
    System.out.println("Processed: " + upper);
};

processName.accept("  alice  "); // Output: Processed: ALICE

This lambda performs three distinct operations: trimming, converting to uppercase, and printing.

Think of It Like This

An expression body is like a sticky note with a quick calculation. A block body is like a full instruction manual—you can have multiple steps, but you need to clearly mark what the final answer is (with return).

Key Takeaway: Use curly braces {} to create a block body when your lambda needs multiple statements; remember to include an explicit return if a value is expected.