Java Lambda Expressions: Syntax, Parameters and Bodies (OCP 21)
Lambda syntax for the OCP 21 exam: why lambdas replace one-method classes, deferred execution, target typing, the optional parentheses, braces, return and semicolon, valid and invalid forms, var and typed parameters, void-compatible bodies, and why var can't hold a lambda.
kvi5hnuCode Sprout team member8 min readOn this page
A lambda expression is a block of code you can pass around like a value. It has parameters and a body, like a method, but no name. You can think of it as a much shorter way to write an anonymous class that implements an interface with a single abstract method (article 44).
Lambdas bring a functional style to Java: you describe what should happen to each element, and let other code decide when and how often to run it. Chapter 8 covers lambdas, functional interfaces and method references, and the next two chapters (collections and streams) use them constantly.
From a class to a lambda
Suppose a method should pick tasks that meet some condition, and the condition varies. A clean design passes the condition in as an object:
record Task(String title, int minutes, boolean urgent) { }
interface TaskCheck {
boolean test(Task t);
}
static List<String> select(List<Task> tasks, TaskCheck check) {
List<String> out = new ArrayList<>();
for (Task t : tasks)
if (check.test(t)) out.add(t.title());
return out;
}
Without lambdas, every new condition needs its own class:
class IsUrgent implements TaskCheck {
public boolean test(Task t) { return t.urgent(); }
}
select(tasks, new IsUrgent());
With a lambda, the condition goes right where it's used:
select(tasks, t -> t.urgent());
select(tasks, t -> t.minutes() > 60);
select(tasks, t -> !t.urgent());
select doesn't change at all. This is called deferred execution: the code is written at the call site, but it runs later, inside select, once for each task.
How Java knows what a lambda means
A lambda has no type of its own. Java works it out from the context, called the target type. In select(tasks, t -> t.urgent()), the second parameter is a TaskCheck, so:
- the lambda implements
TaskCheck's single abstract method,boolean test(Task t) tmust be aTask- the body must produce a
boolean
That's why a lambda can only be used where the target is a functional interface, an interface with exactly one abstract method (next article). Without a usable target, it doesn't compile:
var check = (Task t) -> t.urgent(); // DOES NOT COMPILE: cannot infer type for local variable check
Object o = () -> true; // DOES NOT COMPILE: Object is not a functional interface
Object ok = (TaskCheck) t -> true; // compiles: the cast supplies the target type
Even with the parameter type written out, var has nothing to infer from: the same lambda could implement many different interfaces.
The syntax
Many parts of a lambda are optional. These two lines mean exactly the same thing:
t -> t.urgent()
(Task t) -> { return t.urgent(); }

Every lambda has three parts: a parameter list, the arrow ->, and a body.
Parameters. Parentheses may be left out only when there's exactly one parameter with no declared type:
| Parameters | Valid form |
|---|---|
| none | () -> … (parentheses required) |
| one, no type | x -> … or (x) -> … |
| one, with type | (String x) -> … only |
| two or more | (x, y) -> … or (String x, String y) -> … |
Body. There are two kinds:
- An expression body has no braces. Its value is returned automatically, so there's no
returnkeyword and no semicolon:x -> x.isBlank(). - A block body has braces and contains ordinary statements, each ending in
;. If the lambda returns a value, the block needs areturnstatement:x -> { return x.isBlank(); }.
Braces, return and semicolons come as a package. You can't have return without braces, and you can't leave out return inside braces if a value is expected. The two halves can be mixed freely: x -> { return x.isBlank(); } and (String x) -> x.isBlank() are both fine.
Valid lambdas
Each of these could implement an interface whose method takes String parameters and returns boolean:
| Lambda | Parameters |
|---|---|
() -> false | 0 |
s -> s.contains("@") | 1 |
(String s) -> s.contains("@") | 1 |
(a, b) -> { return a.equals(b); } | 2 |
(String a, String b) -> a.isEmpty() | 2 (ignoring b is fine) |
(var a, var b) -> a.length() > b.length() | 2 |
Invalid lambdas
| Lambda | Problem |
|---|---|
a, b -> a.isEmpty() | two parameters need parentheses |
String s -> s.isEmpty() | a typed parameter needs parentheses |
s -> { s.isEmpty(); } | block body with no return (when a value is expected) |
s -> { return s.isEmpty() } | missing ; inside the braces |
s -> return s.isEmpty(); | return without braces |
(var a, b) -> true | can't mix var with no type |
(String a, b) -> true | can't mix a type with no type |
(var a, String b) -> true | can't mix var with explicit types |
The rule behind the last three is that all parameters must use the same style: all untyped, all var, or all explicit types. Parameter modifiers and the remaining variable rules are covered in article 51.
Bodies that return nothing
When the target method is void, as in Runnable.run(), the body must not produce a value:
Runnable r1 = () -> System.out.println("hi"); // method call: OK
Runnable r2 = () -> { }; // empty block: OK
Runnable r3 = () -> { return; }; // bare return: OK
Runnable r4 = () -> 5; // DOES NOT COMPILE: lambda body is not compatible with a void functional interface
An expression body that is a statement expression (a method call, assignment, ++, -- or new) works for both void and value-returning targets. For a void target, the result is simply discarded. So s -> s.length() can implement a method that returns int, and also one that returns nothing.
The reverse doesn't work. A block that returns nothing can't implement a method that needs a value: Supplier<Integer> s = () -> { }; fails with "bad return type in lambda expression".
Parameter names and scope
A lambda doesn't create a new scope for names the way an anonymous class does. Its parameters and its block's local variables live in the enclosing method's scope, so they can't reuse names already declared there:
void plan() {
String t = "today";
TaskCheck c1 = t -> t.urgent(); // DOES NOT COMPILE: variable t is already defined
TaskCheck c2 = x -> { int x = 1; return true; }; // DOES NOT COMPILE: x is already defined
}
Two parameters can't share a name either, as in (a, a) -> true.
What's current
- Lambda syntax is unchanged since Java 8, and
varparameters have been allowed since Java 11. - Java 22 allows
_for unused lambda parameters. It's on the Java 25 exam, not on 1Z0-830.
Exam traps from this article
A complete example
The program filters a task list with a named class, then with several lambda forms that do the same job. It also shows a block body, a two-parameter lambda, deferred execution, and a zero-parameter Runnable.
import java.util.ArrayList;
import java.util.List;
public class Solution {
record Task(String title, int minutes, boolean urgent) { }
// Our own functional interface: one abstract method
interface TaskCheck {
boolean test(Task t);
}
interface Scorer {
int score(Task a, Task b);
}
static List<String> select(List<Task> tasks, TaskCheck check) {
List<String> out = new ArrayList<>();
for (Task t : tasks) {
if (check.test(t)) out.add(t.title()); // the lambda body runs here, later
}
return out;
}
// Named class: what we'd need without lambdas
static class IsUrgent implements TaskCheck {
public boolean test(Task t) { return t.urgent(); }
}
public static void main(String[] args) {
List<Task> tasks = List.of(
new Task("pay rent", 5, true),
new Task("read novel", 90, false),
new Task("fix bike", 40, true),
new Task("call bank", 15, false));
System.out.println("class: " + select(tasks, new IsUrgent()));
System.out.println("short lambda: " + select(tasks, t -> t.urgent()));
System.out.println("full lambda: " + select(tasks, (Task t) -> { return !t.urgent(); }));
System.out.println("var param: " + select(tasks, (var t) -> t.minutes() <= 15));
// Block body with several statements
TaskCheck quickAndUrgent = t -> {
boolean quick = t.minutes() < 30;
return quick && t.urgent();
};
System.out.println("block body: " + select(tasks, quickAndUrgent));
// Two parameters need parentheses
Scorer longer = (a, b) -> a.minutes() - b.minutes();
System.out.println("novel vs bike: " + longer.score(tasks.get(1), tasks.get(2)));
// Deferred execution: creating the lambda prints nothing
TaskCheck noisy = t -> {
System.out.println(" checking " + t.title());
return t.minutes() > 60;
};
System.out.println("lambda created, nothing checked yet");
System.out.println("long tasks: " + select(tasks, noisy));
// Zero parameters, and a void-compatible body
Runnable done = () -> System.out.println("all " + tasks.size() + " tasks reviewed");
done.run();
}
}
Output:
class: [pay rent, fix bike]
short lambda: [pay rent, fix bike]
full lambda: [read novel, call bank]
var param: [pay rent, call bank]
block body: [pay rent]
novel vs bike: 50
lambda created, nothing checked yet
checking pay rent
checking read novel
checking fix bike
checking call bank
long tasks: [read novel]
all 4 tasks reviewed
Points to notice:
new IsUrgent()andt -> t.urgent()produce the same result. The lambda just skips the class declaration.(Task t) -> { return !t.urgent(); }is the fully written-out form, and(var t) -> …usesvar.quickAndUrgentneeds a block body because it has two statements.- "lambda created, nothing checked yet" prints before any "checking" line. The body only runs when
selectcallstest. Runnabletakes no parameters, so()is required, and theprintlncall fits itsvoidmethod.
Common questions
Is a lambda an object? Yes. At run time a lambda evaluates to an object that implements the functional interface. Its class is generated by the JVM, so you shouldn't rely on its name or identity.
Is a lambda just an anonymous class?
Conceptually it's close, but there are real differences. this inside a lambda means the enclosing object, a lambda can't hold its own fields, and no .class file is generated for it (article 44).
Must I use all the parameters? No. The parameter list must match the interface method, but the body can ignore any of them.
Summary
- A lambda is an unnamed block of code with parameters,
->and a body. It implements the single abstract method of a functional interface. - The target type comes from the context (an assignment, a method argument, a return, or a cast).
varandObjectcan't supply it. - Parentheses are optional only for one untyped parameter. Braces,
returnand;go together. - Parameters must be all untyped, all
varor all explicitly typed, and they can't reuse names of enclosing local variables. - A
voidtarget accepts statement-expression or block bodies without values. A value-returning target needs an expression, or a block withreturn.
Practice quiz
Test yourself with the lambda syntax quiz: 10 exam-style questions with explanations.
Previous: Java Polymorphism: Reference Types, Casting and Virtual Method Calls (OCP 21)
Next: Java Functional Interfaces: The Single Abstract Method Rule (OCP 21)
Related reading
- Symmetric Encryption in Java: AES-GCM, Key Generation and Cipher Streams
- Streaming XML Parsers in Java: SAX and StAX
- Java Directory Traversal: Files.list, walk, find, Glob Patterns and FileVisitor
- Java ZIP Archives: ZipInputStream, ZipOutputStream and ZIP File Systems
- Java I/O Filters: Buffered, Data and Pushback Streams

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.