The target type chooses the overload
parse returns an Integer, so + 1 is arithmetic. show returns a String, so + 1 is concatenation.
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.
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.
Use a constructor reference to turn the names "Asha" and "Ravi" into StringBuilders, reverse each, and print them.
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
What are the four kinds of method reference? Give an example and the equivalent lambda for each.
How does the compiler decide which overload a method reference refers to?
Explain the difference between obj::method and () -> obj.method().
When can't you use a method reference?
Expected output
(0, 0) (3, 3) (1, 2)
8
71