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

Explicit return in Block Bodies

Understand when and how to use explicit return statements in lambda block bodies to return values.

Explicit return in Block Bodies

You'll learn when you must include a return statement inside a multi-line lambda expression.

When your lambda uses a block body (curly braces with multiple statements), Java no longer automatically returns the result. Unlike single-expression lambdas where the value is implicitly returned, block bodies require you to explicitly use the return keyword if your functional interface expects a value.

The Core Rule

  • Expression body: x -> x * 2 — the result is automatically returned
  • Block body: x -> { return x * 2; } — you must write return explicitly

Think of it like the difference between a quick verbal answer versus writing a formal letter. A quick answer doesn't need "My answer is..." preamble, but a structured document needs clear formatting to indicate what you're providing as the result.

When Explicit Return is Required

If your functional interface has a non-void return type (like Function, Predicate, Supplier), and you use braces, you must include return:

Function<Integer, Integer> square = x -> {
    int result = x * x;
    return result;  // REQUIRED
};

Without return, the code won't compile — Java has no way to know which value you intend to send back.

When Return is Optional

If your functional interface returns void (like Consumer), no return is needed or expected:

Consumer<String> printer = s -> {
    String formatted = s.toUpperCase();
    System.out.println(formatted);
    // No return needed - Consumer returns void
};

Key Takeaway: In lambda block bodies, always use explicit return statements when the functional interface expects a value; omit return only for void-returning interfaces.