Skip to content

OCP exam prep: lambda variables

☕ Java 17 · 🎓 OCP 1Z0-829 · How Lambdas See the Variables Around Them

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: Create and use lambda expressions, including local variables and effectively final variables.

Four traps to watch for

Trap 1 — var and types need parentheses

var m -> … and Movie m -> … never compile. Parentheses are optional only for one parameter with no type and no modifier.

Trap 2 — Count the styles in the list

Check every parameter: no type, var, or real type. Any mix, like (var a, b) or (String a, var b), is a compile error.

Trap 3 — Name clashes and semicolons

A lambda parameter or block local can't reuse a name already in scope. In block lambdas, look for the ; after the closing brace.

Trap 4 — Reassigned anywhere = not allowed

A local or parameter changed before or after the lambda can't be used in it. The error points at the lambda, not at the reassignment: read the whole method.

Practice questions

1. Which lambda can fill the blank?

BiPredicate<String, Integer> longTitle = ____________;

A. (var t, n) -> t.length() > n
B. (String t, var n) -> t.length() > n
C. (var t, var n) -> t.length() > n
D. var t, var n -> t.length() > n

Answer

C. Same style for both, in parentheses. A mixes var with no type, B mixes a real type with var, D drops the mandatory parentheses.

2. How many lines cause a compilation error?

1: public void rate(Movie movie) {
2:     double avg = 4.2;
3:     Predicate<Movie> hit = movie -> {
4:         double avg = 4.5;
5:         return movie.rating() > avg; };
6: }

A. None
B. One, line 4
C. Two, lines 3 and 4
D. Three, lines 3, 4 and 5

Answer

C. Line 3 reuses movie, already a method parameter. Line 4 redeclares avg. Line 5 is fine: it ends with };.

3. What is the result of calling start() with a valid User?

1: public void start(User user) {
2:     int profiles = user.profiles();
3:     Supplier<String> info = () -> user.name() + profiles;
4:     profiles++;
5:     System.out.println(info.get());
6: }

A. It prints the name and the original count
B. It prints the name and the count + 1
C. Compiler error on line 3
D. Compiler error on line 4

Answer

C. Line 4 reassigns profiles, so it's no longer effectively final, and the compiler reports it where the lambda uses it: line 3. user never changes, so it's fine.

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