OCP exam prep: method references¶
☕ Java 17 · 🎓 OCP 1Z0-829 · Passing Methods Around by Name
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.
Four traps to watch for¶
Trap 1 — Parentheses after :: never compile
String::length() or title::startsWith("A") are always wrong: a method reference is a name only.
Trap 2 — A class name doesn't mean static
String::isEmpty is an instance method used on the parameter: the interface's first parameter becomes the object.
Trap 3 — Check parameter count and order
Translate to a lambda: String::startsWith for (a, b) means a.startsWith(b). If the counts don't line up, it doesn't compile.
Trap 4 — Fake syntax looks plausible
System::out::println and System.out.println aren't method references. The valid form is System.out::println.
Practice questions¶
1. Which line can replace the lambda with the same behavior?
interface TitleFormatter { String format(String title); }
TitleFormatter f = title -> title.toUpperCase();
A. String::toUpperCase
B. String::toUpperCase()
C. title::toUpperCase
D. String.toUpperCase
Answer
A. The method runs on the parameter: shape 3. B has parentheses, C uses title, which only exists inside the lambda, and D isn't a method reference.
2. What is the result?
1: interface RatingCheck { boolean check(String title, String prefix); }
2: var show = "Dark";
3: RatingCheck r1 = String::startsWith;
4: RatingCheck r2 = show::startsWith;
5: System.out.println(r1.check("Dark", "D"));
A. Prints true
B. Prints false
C. Compiler error on line 3
D. Compiler error on line 4
Answer
D. Line 3 means (t, p) -> t.startsWith(p): fine. Line 4 runs on show, so both parameters would go to startsWith, which has no (String, String) version. Nothing prints.
3. Which statements are true? (Choose two.)
record Series(String name) { }
interface SeriesMaker { Series make(String name); }
SeriesMaker maker = Series::new;
A. Any method reference can become a lambda
B. Any lambda can become a method reference
C. Series::new is a constructor reference
D. System.out::println() compiles
Answer
A and C. A lambda with fixed values or extra logic has no reference form, so B is false. D has parentheses after ::.