Command Palette

Search for a command to run...

Back to the lesson: Topic 10.1 — Lambda Expressions
Core Java · Example 3 of 4 Java 8+

What a lambda can capture, and what this means

The int[] trick works but hides shared mutable state. In real code prefer a return value, a reduction (Topic 10.5) or an AtomicInteger (Topic 13.8).

A lambda expression is a short, nameless function you can store in a variable or pass to a method, like (a, b) -> a + b. It always becomes an object of a functional interface type, and it can read local variables only if they are effectively final.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write static void repeat(int times, Runnable action) and use it to print Hello 1, Hello 2, Hello 3 using a counter held in an int[].

02

Sort List.of("kiwi", "fig", "banana", "apple") (copied into an ArrayList) by length, and alphabetically for equal lengths, using one lambda comparator. Print the list.

03

Write static Function<Integer, Integer> adder(int n) that returns a lambda adding n. Create add5 and add10 and print add5.apply(1), add10.apply(1) and add5.apply(add10.apply(0)).

Explain it without notes

01

What is a lambda expression, and what decides its type?

02

Why must captured local variables be effectively final, while fields can change?

03

How does this behave inside a lambda compared with an anonymous class?

04

How does the JVM create a lambda object at runtime?

What a lambda can capture, and what this means Java 8+
Sign in to run this example in your browser.

Expected output

lambda this:    field of Main / local variable
anonymous this: field of the anonymous class / local variable
counter: 3
captured value: 101