Bound instance references
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)You write x -> System.out.println(x) again and again, always on the same object. There is a shorter way when the object is already known.
System.out::println: the object is fixed first
Bound reference is a method reference written object::method. The object, called the receiver, is fixed when the reference is created, so the interface needs no input for it.
A bound instance reference has an object, not a class, on the left of ::. System.out is an object: the PrintStream that writes to the console. System.out::println means "call println on this exact object".
Example 1 · Bound references on System.out, a String and a list
import java.util.ArrayList;import java.util.List;import java.util.function.Consumer;import java.util.function.Predicate;import java.util.function.Supplier;
public class BoundBasicsDemo { public static void main(String[] args) { Consumer<String> print = System.out::println; // receiver: System.out
String prefix = "IND"; Predicate<String> isPrefixOf = prefix::startsWith; // s -> prefix.startsWith(s) Supplier<Integer> prefixLength = prefix::length;
List<String> smsLog = new ArrayList<>(); Consumer<String> save = smsLog::add; // msg -> smsLog.add(msg)
print.accept("IN is a start of IND: " + isPrefixOf.test("IN")); print.accept("Length of prefix: " + prefixLength.get());
save.accept("OTP 4821 sent"); save.accept("OTP 9930 sent"); print.accept("Saved: " + smsLog); }}IN is a start of IND: true Length of prefix: 3 Saved: [OTP 4821 sent, OTP 9930 sent]
What this code does
- In every reference here the object on the left is fixed:
System.out, theStringinprefixand the list insmsLog. Each input of the interface becomes an argument. - That is why
prefix::startsWithasks whetherprefixstarts with the input, not the other way round.prefix::lengthtakes no input at all, so it fitsSupplier<Integer>.
The object a method runs on is called the receiver. In a bound reference the receiver is chosen when the reference is created, so it is "bound" to it. Every input of the interface goes to the method as an argument. Consumer<String> print = System.out::println; is the same as s -> System.out.println(s). Any expression that gives an object can stand on the left: a variable like smsLog::add, a field like this.rules::check, or a call like getLogger()::info.
object::method and this::method
Write object::method when you already have the object that should do the work. If validator is a MobileValidator, then validator::isValid is a Predicate<String> that asks that validator about each number. Different validator objects, with different settings, give different predicates.
Example 2 · object::method with two validators, and this::method
import java.util.ArrayList;import java.util.List;import java.util.function.Predicate;
class MobileValidator { private final String allowedStart;
MobileValidator(String allowedStart) { this.allowedStart = allowedStart; }
boolean isValid(String number) { return number.length() == 10 && allowedStart.indexOf(number.charAt(0)) >= 0; }}
class OrderDesk { private final List<String> log = new ArrayList<>();
private void record(String order) { log.add("received " + order); }
void takeAll(List<String> orders) { orders.forEach(this::record); // order -> this.record(order) System.out.println(log); }}
public class ObjectAndThisDemo { public static void main(String[] args) { MobileValidator india = new MobileValidator("6789"); MobileValidator onlyNine = new MobileValidator("9");
List<String> numbers = List.of("9876543210", "6123456789", "12345", "5123456789"); Predicate<String> indiaRule = india::isValid; Predicate<String> nineRule = onlyNine::isValid;
for (String n : numbers) { System.out.println(n + " india=" + indiaRule.test(n) + " nine=" + nineRule.test(n)); }
new OrderDesk().takeAll(List.of("ORD-1", "ORD-2")); }}9876543210 india=true nine=true 6123456789 india=true nine=false 12345 india=false nine=false 5123456789 india=false nine=false [received ORD-1, received ORD-2]
What this code does
india::isValidandonlyNine::isValidname the same method but on different objects. Each predicate carries its own validator, with its ownallowedStartsetting.- Inside
OrderDesk,this::recordpasses the current object's private method toforEach. A method reference can reach private methods wherever normal code in that class could call them.
validator::isValidiss -> validator.isValid(s), aPredicate<String>.this::recordismsg -> this.record(msg), often aConsumer<String>.blocked::containson aSet<String>isid -> blocked.contains(id).prices::geton aMap<String, Integer>isitem -> prices.get(item).
Inside a class, this::method refers to a method of the current object. It is the short form of x -> this.method(x). It is common in a class that passes one of its own methods to forEach, removeIf or sort. super::method works the same way and calls the parent class version.
Real-world use: pass an object's behaviour into a pipeline
Real code often has helper objects: a validator, a logger, a set of blocked UPI ids, a price list. The caller plugs their behaviour in with bound references: process(payments, validator::isValid, logger::info).
Example 3 · Real use: a payment pipeline with validator::isValid and logger::info
import java.util.ArrayList;import java.util.List;import java.util.Set;import java.util.TreeSet;import java.util.function.Consumer;import java.util.function.Predicate;
class UpiValidator { boolean isValid(String upiId) { int at = upiId.indexOf('@'); return at > 0 && at < upiId.length() - 1; }}
class AuditLog { private final List<String> lines = new ArrayList<>();
void info(String message) { lines.add("INFO " + message); }
void printAll() { lines.forEach(System.out::println); }}
public class PaymentPipelineDemo { static List<String> process(List<String> payees, Predicate<String> isValid, Predicate<String> isBlocked, Consumer<String> report) { List<String> accepted = new ArrayList<>(); for (String p : payees) { if (!isValid.test(p)) { report.accept("rejected bad id " + p); } else if (isBlocked.test(p)) { report.accept("rejected blocked id " + p); } else { accepted.add(p); } } return accepted; }
public static void main(String[] args) { UpiValidator validator = new UpiValidator(); AuditLog logger = new AuditLog(); Set<String> blocked = new TreeSet<>(Set.of("spam@ybl"));
List<String> payees = List.of("ravi@okbank", "meera@", "spam@ybl", "asha@upi"); List<String> ok = process(payees, validator::isValid, blocked::contains, logger::info);
System.out.println("Accepted: " + ok); logger.printAll(); }}Accepted: [ravi@okbank, asha@upi] INFO rejected bad id meera@ INFO rejected blocked id spam@ybl
What this code does
processonly knows three interfaces. The caller decides the real behaviour with bound references to its own objects: a validator, a set of blocked ids and a logger.blocked::containsturns aSetinto aPredicate<String>, andlogger::infoturns the log into aConsumer<String>. Swapping in a different logger object changes where messages go without touchingprocess.
A method can take such behaviour as functional interfaces, so the processing method does not know which validator or logger it got.
For example, a Predicate<String> can mean "is it valid" and a Consumer<String> can mean "report a problem". Swap in a stricter validator or a test logger, and nothing else changes. This is how frameworks are built. Your code hands over small pieces of behaviour, and the framework calls them at the right time.
Trap: the receiver is evaluated once
Java works out the receiver when the reference is created, not each time it is used. The two results of this rule surprise many learners.
Example 4 · Trap: a null receiver fails at once, a lambda fails later
import java.util.function.Supplier;
public class NullReceiverDemo { public static void main(String[] args) { String coupon = null; // the user did not enter a coupon
Supplier<Integer> lazy = () -> coupon.length(); System.out.println("Lambda created");
try { Supplier<Integer> eager = coupon::length; System.out.println("Reference created"); } catch (NullPointerException e) { System.out.println("Reference failed on the line that created it"); }
try { System.out.println(lazy.get()); } catch (NullPointerException e) { System.out.println("Lambda failed only when get() ran"); } }}Lambda created Reference failed on the line that created it Lambda failed only when get() ran
What this code does
- For
coupon::lengthJava checks the receiver straight away.couponisnull, so the line that creates the reference throws, and"Reference created"never prints. - The lambda reads
coupononly when its body runs. Creating it is fine; the exception comes fromlazy.get(). So a bound reference reports a missing object early, which is often easier to debug.
Example 5 · Reading the stack trace of a null receiver
import java.util.function.Consumer;
public class NullTraceDemo { static Consumer<String> printerFor(StringBuilder target) { return target::append; }
public static void main(String[] args) { StringBuilder report = null; // forgot: new StringBuilder() Consumer<String> add = printerFor(report); add.accept("Attendance 92%"); }}Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:233) at NullTraceDemo.printerFor(NullTraceDemo.java:5) at NullTraceDemo.main(NullTraceDemo.java:10)
What this code does
- The trace points at
Objects.requireNonNulland then at thereturn target::append;line. Java inserted that null check where the reference is created, so the failure shows where the object was missing, not where it was used. - Fix: make sure the receiver exists before you create the reference, here
StringBuilder report = new StringBuilder();. The line numbers insidejava.basecan differ between Java versions.
Example 6 · The reference keeps the object, not the variable
import java.util.function.Supplier;
public class ReceiverOnceDemo { public static void main(String[] args) { StringBuilder slip = new StringBuilder("Fee slip"); Supplier<String> show = slip::toString; // receiver chosen now
slip.append(" - paid"); System.out.println(show.get());
slip = new StringBuilder("New slip"); System.out.println(show.get()); System.out.println(slip);
// Supplier<String> lam = () -> slip.toString(); // would not compile: slip is not effectively final }}Fee slip - paid Fee slip - paid New slip
What this code does
showholds the firstStringBuilderobject. Appending to that object is visible throughshow, because it is still the same object.- Giving
slipa new object does not affectshow: the receiver was evaluated once. A lambda could not even usesliphere, because the variable is reassigned and so is not effectively final.
First, a null receiver fails at once. Supplier<Integer> s = coupon::length; with coupon == null throws NullPointerException on that very line, even if get() is never called. The lambda () -> coupon.length() is created without trouble and fails only when it runs. Second, the reference keeps the object, not the variable. If the variable later points to a new object, the reference still uses the old one. Changes made inside that same object are still seen, because it is the same object.
Predict the output
When is the object fixed?
Read the code, then pick what it prints.
Round 1 of 3
Next step
Check your understanding
11 quick questions