ConceptDifficulty: Intermediate1 min

A Return Type That Says There Might Be Nothing Here

A method called findByReference returns a Customer. Whether it can return null is written in the documentation, if anywhere, and the compiler will not help you either way.

java
Customer findByReference(String ref);

Customer c = findByReference(ref);
System.out.println(c.name());
line 4 is either correct or a NullPointerException, and the signature does not say

Optional<Customer> moves that fact into the signature. It is a container holding either one value or nothing, and a caller cannot reach the value without acknowledging that it might be absent.

java
Optional<Customer> findByReference(String ref);

String name = findByReference(ref)
        .map(Customer::name)
        .orElse("unknown");
What each return type tells the caller
Signature saysCaller learns
CustomerNothing about absence; must read the documentation or guess
Optional<Customer>Absence is expected, and the compiler will not let it be ignored

So Optional is a documentation mechanism the compiler enforces. It exists for exactly one job — a method saying "there might be nothing to return" in a way a caller cannot miss.