Unbound instance references
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)In a list of names you want each name's length, and the object is different every time. How can one short form work for every element?
The first argument becomes the object
Unbound reference is written ClassName::instanceMethod, such as String::length. No object is fixed yet: the first input of the interface becomes the object, and the other inputs become the method arguments.
An unbound instance reference names an instance method through its class: String::length, String::toUpperCase, Student::marks. No object is fixed yet; it is "unbound". The object arrives later, as the first input of the interface method.
Example 1 · One-input forms: length, toUpperCase, isBlank
import java.util.ArrayList;import java.util.List;import java.util.function.Function;import java.util.function.Predicate;import java.util.function.UnaryOperator;
public class UnboundBasicsDemo { public static void main(String[] args) { Function<String, Integer> length = String::length; // s -> s.length() UnaryOperator<String> upper = String::toUpperCase; // s -> s.toUpperCase() Predicate<String> blank = String::isBlank; // s -> s.isBlank()
System.out.println(length.apply("Pune") + " " + upper.apply("pune") + " " + blank.test(" "));
List<String> branches = new ArrayList<>(List.of("cse", " ", "ece", "", "mech")); branches.removeIf(String::isBlank); branches.replaceAll(String::toUpperCase); System.out.println(branches);
for (String b : branches) { System.out.println(b + " has " + length.apply(b) + " letters"); } }}4 PUNE true [CSE, ECE, MECH] CSE has 3 letters ECE has 3 letters MECH has 4 letters
What this code does
- In
length.apply("Pune"), the input"Pune"becomes the object andlength()runs on it. Nothing was fixed in advance, so the samelengthworks on every branch name. removeIfandreplaceAllhand each list item in as the first input, which makesString::isBlankandString::toUpperCasefit perfectly.
Trace Function<String, Integer> f = String::length; with f.apply("Pune"). apply receives "Pune". Java uses that first input as the receiver and calls "Pune".length(), which returns 4. So String::length is the short form of s -> s.length(). The rule for the shape: the interface has one more input than the method has parameters. length() takes none, so it fits a one-input interface like Function<String, Integer>, ToIntFunction<String> or, with a boolean method like isBlank, a Predicate<String>.
replaceAll(String::trim) and removeIf(String::isBlank) hand each item in as the object.Two-argument forms
When the method takes one parameter, the interface needs two inputs. The first input is the object, the second is the argument. String::compareToIgnoreCase becomes (a, b) -> a.compareToIgnoreCase(b), which is exactly the shape of Comparator<String>.
Example 2 · Two-input forms and why the order matters
import java.util.ArrayList;import java.util.List;import java.util.function.BiFunction;import java.util.function.BiPredicate;
public class TwoInputDemo { public static void main(String[] args) { List<String> names = new ArrayList<>(List.of("kavya", "Arjun", "zoya", "Bala", "aditi")); names.sort(String::compareTo); System.out.println("compareTo: " + names); names.sort(String::compareToIgnoreCase); // (a, b) -> a.compareToIgnoreCase(b) System.out.println("compareToIgnoreCase: " + names);
BiFunction<String, String, Boolean> startsWith = String::startsWith; BiPredicate<String, String> sameName = String::equalsIgnoreCase; System.out.println(startsWith.apply("TN-09-AB-1234", "TN") + " " + sameName.test("RAVI", "ravi"));
BiPredicate<String, String> contains = String::contains; System.out.println(contains.test("banana", "nan")); // "banana".contains("nan") System.out.println(contains.test("nan", "banana")); // "nan".contains("banana") }}compareTo: [Arjun, Bala, aditi, kavya, zoya] compareToIgnoreCase: [aditi, Arjun, Bala, kavya, zoya] true true true false
What this code does
- With two inputs, the first is the object and the second is the argument.
String::compareToIgnoreCaseis therefore a ready-madeComparator<String>. contains.test("nan", "banana")asks whether"nan"contains"banana", which is false. Swapped inputs compile fine and give wrong answers, so read the first input as "the object".
The same goes for BiFunction<String, String, Boolean> starts = String::startsWith;, which is (text, start) -> text.startsWith(start), and BiPredicate<String, String> same = String::equalsIgnoreCase;. The order is fixed: first input is the object, the rest are arguments in order. With String::contains, test("banana", "nan") asks whether "banana" contains "nan". Swap the inputs and you ask the opposite question, a bug that compiles without any warning.
Predict the output
Which argument is the object?
Read the code, then pick what it prints.
Round 1 of 2
Record accessors and getters with Comparator.comparing
The most common unbound references in real code are getters and record accessors. A record accessor is the method a record makes for each component: record Student(String name, int marks) gets name() and marks().
Example 3 · Record accessors in Comparator.comparing
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
record Student(String name, String branch, int marks) {}
public class RankListDemo { public static void main(String[] args) { List<Student> list = new ArrayList<>(); list.add(new Student("Meera", "ECE", 88)); list.add(new Student("Arjun", "CSE", 92)); list.add(new Student("Bala", "CSE", 88)); list.add(new Student("Divya", "ECE", 95));
// highest marks first, ties by name list.sort(Comparator.comparingInt(Student::marks).reversed() .thenComparing(Student::name)); list.forEach(s -> System.out.println(s.marks() + " " + s.name()));
// branch A to Z, then marks high to low list.sort(Comparator.comparing(Student::branch) .thenComparing(Comparator.comparingInt(Student::marks).reversed())); System.out.println(); list.forEach(s -> System.out.println(s.branch() + " " + s.name() + " " + s.marks())); }}95 Divya 92 Arjun 88 Bala 88 Meera CSE Arjun 92 CSE Bala 88 ECE Divya 95 ECE Meera 88
What this code does
Student::marksiss -> s.marks(), a key extractor that fitscomparingInt.Student::namefitscomparingandthenComparing. The chain reads like the rule it implements.comparingInt(Student::marks).reversed()compiles without writing any types. The reference namesStudent, so Java knows the type even though.reversed()follows. The lambda forms -> s.marks()would lose it.
Example 4 · Getters on a normal class, passed to a generic method
import java.util.List;import java.util.function.Function;import java.util.function.ToIntFunction;
class Book { private final String title; private final int price;
Book(String title, int price) { this.title = title; this.price = price; }
String getTitle() { return title; }
int getPrice() { return price; }}
public class GetterReferenceDemo { static <T> void printColumn(List<T> items, Function<T, String> column) { for (T item : items) { System.out.println("- " + column.apply(item)); } }
static <T> int total(List<T> items, ToIntFunction<T> amount) { int sum = 0; for (T item : items) { sum += amount.applyAsInt(item); } return sum; }
public static void main(String[] args) { List<Book> cart = List.of(new Book("Let Us C", 350), new Book("Head First Java", 699), new Book("Data Structures", 450)); printColumn(cart, Book::getTitle); System.out.println("Total: Rs " + total(cart, Book::getPrice)); }}- Let Us C - Head First Java - Data Structures Total: Rs 1499
What this code does
printColumnandtotalwork for any typeT.Book::getTitlefitsFunction<Book, String>andBook::getPricefitsToIntFunction<Book>, soTbecomesBook.- Getters are the most frequent unbound references you will write. Passing "which field" as a reference lets one helper method serve every class.
Comparator.comparing(Student::name) reads as "compare students by name". Comparator.comparingInt(Student::marks) compares the int marks without boxing. Chains read like a sentence: comparingInt(Student::marks).reversed().thenComparing(Student::name). There is a bonus. The Collections section showed that comparing(s -> s.getCgpa()).reversed() fails, because the lambda's parameter type is lost. comparing(Student::cgpa).reversed() compiles, because the reference names the class Student itself.
Bound or unbound: String::length versus str::length
The left side of :: decides the kind. If it is a type, such as String, the reference is static or unbound. If it is an expression that gives an object, such as str or System.out, it is bound.
Example 5 · Bound and unbound side by side
import java.util.function.Function;import java.util.function.Predicate;import java.util.function.Supplier;
public class BoundVsUnboundDemo { public static void main(String[] args) { String city = "Chennai";
Supplier<Integer> boundLength = city::length; // () -> city.length() Function<String, Integer> unboundLength = String::length; System.out.println(boundLength.get() + " " + unboundLength.apply("Ooty"));
Predicate<String> cityStartsWith = city::startsWith; // p -> city.startsWith(p) Predicate<String> isEmpty = String::isEmpty; // s -> s.isEmpty() System.out.println(cityStartsWith.test("Che") + " " + isEmpty.test("")); }}7 4 true true
What this code does
city::lengthalready has its object, so it takes no input and is aSupplier.String::lengthwaits for its object, so it takes one input and is aFunction.- With
Predicate<String>,city::startsWithuses the input as the argument, whileString::isEmptyuses the input as the object. Same interface, different roles for the input.
Example 6 · Mistake: an unbound reference where no object is given
import java.util.function.Supplier;
public class UnboundMistakeDemo { public static void main(String[] args) { String city = "Chennai"; Supplier<Integer> size = String::length; System.out.println(size.get()); }}UnboundMistakeDemo.java:6: error: incompatible types: invalid method reference
Supplier<Integer> size = String::length;
^
unexpected instance method length() found in unbound lookup
1 errorWhat this code does
Supplier.get()gives no input, butString::lengthneeds a String to run on. Java has no object to calllengthon and reports "unexpected instance method length() found in unbound lookup".- Fix: use the bound form
city::lengthfor aSupplier, or keepString::lengthand change the type toFunction<String, Integer>.
String::length→s -> s.length()→Function<String, Integer>, works on any String.str::length→() -> str.length()→Supplier<Integer>, works on one String.String::startsWith→(s, p) -> s.startsWith(p)→BiFunctionorBiPredicate.str::startsWith→p -> str.startsWith(p)→Predicate<String>.
String::length has no object yet, so it needs one input: it is a Function<String, Integer>. str::length already has its object, so it needs no input: it is a Supplier<Integer>. The same method, two very different shapes.
Next step
Check your understanding
12 quick questions