Optional: practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most Optional bugs come from a handful of habits: calling get() without thinking, putting a costly call inside orElse, wrapping a possible null with of, and using map where flatMap is needed. Each has a short, reliable fix.
Mistake 1: get on an empty Optional
opt.get() throws NoSuchElementException: No value present when the box is empty. It usually hides in code written for the "happy path", where the tester always used data that existed.
Example 1 · Mistake: get on an empty Optional
import java.util.Map;import java.util.NoSuchElementException;import java.util.Optional;
public class GetMistakeDemo { static Map<String, String> shelfOf = Map.of("Godan", "S-12", "Gitanjali", "P-03");
static Optional<String> findShelf(String title) { return Optional.ofNullable(shelfOf.get(title)); }
public static void main(String[] args) { try { System.out.println("Wrong: " + findShelf("Nirmala").get()); } catch (NoSuchElementException e) { System.out.println("Wrong: crashed with " + e.getMessage()); }
System.out.println("Fixed: " + findShelf("Nirmala").orElse("not in library")); System.out.println("Fixed: " + findShelf("Godan").orElse("not in library")); }}Wrong: crashed with No value present Fixed: not in library Fixed: S-12
What this code does
get()worked in every test that used a book in the library. The first missing title crashes the program.- A missing book is a normal outcome here, so
orElsewith a message is the right fix. If it were an error,orElseThrowwith a clear exception would be.
The fix depends on what the empty case means. A normal "not found" gets a default with orElse or an action with ifPresentOrElse. A real error gets orElseThrow(() -> new XException("...")), which at least says clearly what was missing.
Mistake 2: orElse with an expensive call
orElse(loadFromDatabase(id)) runs loadFromDatabase on every call, even when the value is present, because Java evaluates arguments before calling the method. The program gives correct answers, so the bug shows up only as slow pages, extra database load or, with side effects, duplicate records.
Example 2 · Mistake: orElse with an expensive call
import java.util.List;import java.util.Map;import java.util.Optional;
public class ExpensiveOrElseDemo { static Map<String, Integer> cachedFines = Map.of("M1", 0, "M2", 40, "M3", 10); static int slowCalls = 0;
static int computeFineSlowly(String member) { slowCalls++; // pretend: reads every loan from the database return 25; }
public static void main(String[] args) { List<String> members = List.of("M1", "M2", "M3", "M4");
int total = 0; for (String m : members) { total += Optional.ofNullable(cachedFines.get(m)).orElse(computeFineSlowly(m)); } System.out.println("Wrong: total " + total + ", slow calls " + slowCalls);
slowCalls = 0; total = 0; for (String m : members) { total += Optional.ofNullable(cachedFines.get(m)).orElseGet(() -> computeFineSlowly(m)); } System.out.println("Fixed: total " + total + ", slow calls " + slowCalls); }}Wrong: total 75, slow calls 4 Fixed: total 75, slow calls 1
What this code does
- Both loops give the same total, so tests that check only the answer pass. The wrong one ran the slow method for all 4 members; only M4 actually needed it.
orElseGetreceives a lambda and calls it only for the empty case, so the slow work happens once.
The fix is orElseGet(() -> loadFromDatabase(id)). Keep orElse for constants and values already in a variable.
Mistake 3: of where ofNullable is needed, or returning null
Optional.of(map.get(key)) throws a NullPointerException as soon as the key is missing, which is exactly the case the Optional was meant to handle. Anything that can be null, such as Map.get, an unset field or an old API, needs Optional.ofNullable.
Example 3 · Mistake: Optional.of on a value that can be null
import java.util.Map;import java.util.Optional;
public class OfMistakeDemo { static Map<String, String> phoneOf = Map.of("Aarti", "9800011122");
static Optional<String> phoneWrong(String member) { return Optional.of(phoneOf.get(member)); }
static Optional<String> phoneFixed(String member) { return Optional.ofNullable(phoneOf.get(member)); }
public static void main(String[] args) { System.out.println("Wrong, Aarti: " + phoneWrong("Aarti")); try { System.out.println("Wrong, Balu: " + phoneWrong("Balu")); } catch (NullPointerException e) { System.out.println("Wrong, Balu: NullPointerException"); } System.out.println("Fixed, Balu: " + phoneFixed("Balu")); }}Wrong, Aarti: Optional[9800011122] Wrong, Balu: NullPointerException Fixed, Balu: Optional.empty
What this code does
Map.getreturnsnullfor Balu, andOptional.of(null)throws at once. The method crashes in the one case it was written to handle.ofNullableturns thatnullintoOptional.empty, so the caller decides what to do.
The mirror mistake is return null; inside a method that returns Optional. Callers trust the type, call orElse on null and crash. Return Optional.empty() on every "not found" path.
Mistake 4: map where flatMap is needed
If a getter already returns an Optional, map wraps it again and you get Optional<Optional<T>>. The code then fails to compile at the next step, or prints Optional[Optional[...]]. Use flatMap for functions that return an Optional and map for functions that return a plain value.
Example 4 · Mistake: map where flatMap is needed
import java.util.Map;import java.util.Optional;
public class MapMistakeDemo { static Map<String, String> borrowerOf = Map.of("ISBN-1", "Chandni", "ISBN-2", "Dhruv"); static Map<String, String> phoneOf = Map.of("Chandni", "9811122233");
static Optional<String> findBorrower(String isbn) { return Optional.ofNullable(borrowerOf.get(isbn)); }
static Optional<String> findPhone(String member) { return Optional.ofNullable(phoneOf.get(member)); }
public static void main(String[] args) { System.out.println("Wrong: " + findBorrower("ISBN-1").map(MapMistakeDemo::findPhone));
for (String isbn : new String[] {"ISBN-1", "ISBN-2", "ISBN-3"}) { String phone = findBorrower(isbn) .flatMap(MapMistakeDemo::findPhone) .orElse("no phone to call"); System.out.println("Fixed, " + isbn + ": " + phone); } }}Wrong: Optional[Optional[9811122233]] Fixed, ISBN-1: 9811122233 Fixed, ISBN-2: no phone to call Fixed, ISBN-3: no phone to call
What this code does
findPhonealready returns an Optional, somapgives a box inside a box, andorElse("...")on it would not compile.flatMapreturns the inner Optional directly. OneorElsenow covers a borrower without a phone (ISBN-2) and a book nobody borrowed (ISBN-3).
The same idea removes nested null checks: make the getters return Optionals, chain them with flatMap, and finish with one orElse, orElseThrow or ifPresentOrElse.
Finish up
Mark complete & continue
Next: Dates with LocalDate