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.
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[].
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.
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
What is a lambda expression, and what decides its type?
Why must captured local variables be effectively final, while fields can change?
How does this behave inside a lambda compared with an anonymous class?
How does the JVM create a lambda object at runtime?
Expected output
lambda this: field of Main / local variable
anonymous this: field of the anonymous class / local variable
counter: 3
captured value: 101