Command Palette

Search for a command to run...

Back to the lesson: Topic 10.3 — Method References
Core Java · Example 2 of 4 Java 8+

Bound receivers are evaluated once, lambdas every time

viaRef still points at the String "first"; the field now points somewhere else.

A method reference like String::length or System.out::println is a shorter way to write a lambda that only calls one existing method. There are four kinds: static, bound instance, unbound instance and constructor references.

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.

01

Given List<String> words = List.of("pear", "Apple", "fig"), copy it into an ArrayList, sort it case-insensitively using an unbound method reference, and print it. Then print each word with forEach and a bound reference.

02

Use a constructor reference to turn the names "Asha" and "Ravi" into StringBuilders, reverse each, and print them.

03

Write a class Checker with an instance method boolean isShort(String s) (length below 4) and a method List<String> keepShort(List<String> in) that uses this::isShort with removeIf and Predicate.not. Test it on pear, fig, kiwi, ox.

Explain it without notes

01

What are the four kinds of method reference? Give an example and the equivalent lambda for each.

02

How does the compiler decide which overload a method reference refers to?

03

Explain the difference between obj::method and () -> obj.method().

04

When can't you use a method reference?

Bound receivers are evaluated once, lambdas every time Java 8+
Sign in to run this example in your browser.

Expected output

method reference: 5
lambda:           12
lambda over null: created fine
method reference over null: NPE at creation
lambda over null: NPE only when called