Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Lambda expression: ->

The -> symbol separates a lambda's parameters from its body. A lambda describes behavior for a functional interface; its body executes when the appropriate method is called, not when the lambda is assigned.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

() -> expression
parameter -> expression
(parameter1, parameter2) -> expression
(int parameter) -> { return expression; }

In a lambda expression, -> separates the parameters from the body. Parentheses may be omitted only when the sole parameter is written as a bare identifier: x -> x + 1. A parameter declared with var still has an inferred type, but it requires parentheses: (var x) -> x + 1. With no parameters, write (); multiple parameters require parentheses, for example (x, y) -> x + y.

A lambda's target type can be a functional interface or an intersection type that induces a functional interface. The function type of the target type determines the parameter and result types. The target type can come from an assignment, an invocation argument, or a cast. For example, a cast can specify Runnable & java.io.Serializable as the target type. The @FunctionalInterface annotation is not required.

The body can be an expression or a block. For a numeric result, x -> x + 1 corresponds to x -> { return x + 1; }. Captured local variables must be final or effectively final, meaning they cannot be reassigned after initialization.

In the example, IntUnaryOperator accepts an int and returns an int. Assignment to doubleValue does not execute the lambda body; calling applyAsInt(7) does, producing 14.

Examples

import java.util.function.IntUnaryOperator;

public class Main {
    public static void main(String[] args) {
        IntUnaryOperator doubleValue = value -> value * 2;
        System.out.println(doubleValue.applyAsInt(7));
    }
}

Result

14

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources