Skip to content

OCP exam prep: lambda syntax

☕ Java 17 · 🎓 OCP 1Z0-829 · Passing Behavior Around with Lambdas

Optional page

This page is for readers preparing the Oracle Certified Professional Java SE 17 Developer exam (1Z0-829). The concepts are all you need otherwise.

Exam objective: Use Java object and primitive streams, including lambda expressions implementing functional interfaces.

Four traps to watch for

Trap 1 — Count the parentheses

m, s -> … and Movie m -> … don't compile. Parentheses may be dropped only for exactly one untyped parameter. (m) -> … is legal.

Trap 2 — Braces bring return and ;

m -> { m.isNew() } fails twice: no return, no ;. With braces you need both; without braces, neither.

Trap 3 — No var for lambdas

var f = (Movie m) -> m.isNew(); doesn't compile, even with a typed parameter. A lambda needs a target type.

Trap 4 — Strange but legal

() -> true, m -> {} and lambdas that ignore a parameter all compile. Don't reject an answer just because it looks unusual.

Practice questions

1. Which lambda can replace the comment so that the code compiles?

public interface MovieFilter { boolean test(Movie movie); }
print(catalog, /* INSERT LAMBDA HERE */);

A. Movie m -> m.isNew()
B. m -> { return m.isNew() }
C. (m) -> m.isKidFriendly()
D. m -> { m.isNew(); }

Answer

C. Parentheses around one untyped parameter are optional, not forbidden. A needs parentheses for the type, B misses the ;, and D never returns the boolean.

2. Which lambdas can be assigned to rule? (Choose all that apply.)

interface EpisodeCheck { boolean check(String title, int minutes); }
EpisodeCheck rule = /* INSERT LAMBDA HERE */;

A. (t, m) -> m > 40
B. t, m -> m > 40
C. (t, m) -> { return t.isEmpty(); }
D. (String t, int m) -> { m > 40; }

Answer

A and C. C ignores m, which is fine. B forgets the parentheses around two parameters. D has braces without return, and m > 40; isn't even a valid statement.

3. Which line does NOT compile?

1: MovieFilter a = m -> m.isNew();
2: MovieFilter b = (Movie m) -> m.isKidFriendly();
3: var c = (Movie m) -> m.isNew();
4: MovieFilter d = m -> { return !m.isNew(); };

A. Line 1
B. Line 2
C. Line 3
D. Line 4

Answer

C. With var, the lambda has no target type, even with a typed parameter. The other lines give it MovieFilter.

← Back to the series · All 1Z0-829 pages