Optional: Correct and Incorrect Use
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Almost every Java interview has an Optional question, and it is rarely "what is Optional?". The interviewer wants to hear whether you use it as a return type for a missing result, or as a fancy null check.
Why Optional exists
Optional<T> is a container that holds either one non-null value or nothing. It is mainly a method's return type, used when "no result" is a normal answer, so the caller must decide what to do in the empty case.
A repository method findById may find nothing. With a plain null the caller can forget to check; with Optional the empty case is part of the return type.
Example 1 · null crashes later, Optional forces a decision
import java.util.Map;import java.util.Optional;
public class WhyOptionalDemo { static Map<Integer, String> students = Map.of(101, "Asha", 102, "Ravi");
static String findNameOrNull(int roll) { return students.get(roll); // null when missing }
static Optional<String> findName(int roll) { return Optional.ofNullable(students.get(roll)); // empty when missing }
public static void main(String[] args) { String n = findNameOrNull(105); try { System.out.println(n.toUpperCase()); } catch (NullPointerException e) { System.out.println("null version crashed: NullPointerException"); }
System.out.println(findName(101).map(String::toUpperCase).orElse("NOT FOUND")); System.out.println(findName(105).map(String::toUpperCase).orElse("NOT FOUND")); System.out.println("Is 105 present? " + findName(105).isPresent()); }}null version crashed: NullPointerException ASHA NOT FOUND Is 105 present? false
What this code does
findNameOrNull(105)returnsnull, and the crash happens later atn.toUpperCase(), far from the lookup. Nothing in the method's signature warned the caller.findNamereturnsOptional<String>, so the caller writesmap(...).orElse("NOT FOUND")and the missing roll number becomes a normal, handled case.
Model answer, spoken: "Optional is a return type for methods that may not have a result, like findById. It makes the empty case visible in the API and gives safe ways to handle it, like orElse, map and orElseThrow. It is not meant to replace every null, and it is not meant for fields or parameters." Revise: Why Optional (opens in a new tab).
Must know:
- Create with
Optional.of(v)(v must not be null),Optional.ofNullable(v)(null gives empty),Optional.empty(). - Read with
orElse,orElseGet,orElseThrow,ifPresent,ifPresentOrElse(Java 9),isPresent,isEmpty(Java 11). - Transform with
map,flatMap,filter,or(Java 9),stream()(Java 9). - Primitive versions:
OptionalInt,OptionalLong,OptionalDouble(fromIntStream.max()and friends).
orElse vs orElseGet: the eager-evaluation trap
orElse(value) returns the value inside an Optional, or the default you pass when it is empty. Java evaluates the default before the call, so it is computed even when the Optional already has a value.
A default value can be a constant or a costly call. See what orElse does with a method call, then how orElseGet changes it.
Example 2 · Predict the output: orElse creates an account anyway
import java.util.HashMap;import java.util.Map;import java.util.Optional;
public class OrElseTrapDemo { static Map<String, String> accounts = new HashMap<>(); static int created = 0;
static Optional<String> findAccount(String phone) { return Optional.ofNullable(accounts.get(phone)); }
static String createAccount(String phone) { created++; System.out.println(" creating account for " + phone); return "ACC-" + phone.substring(6); }
public static void main(String[] args) { accounts.put("9876543210", "ACC-3210");
System.out.println("orElse:"); String a = findAccount("9876543210").orElse(createAccount("9876543210")); System.out.println(" got " + a + ", accounts created so far: " + created);
System.out.println("orElseGet:"); String b = findAccount("9876543210").orElseGet(() -> createAccount("9876543210")); System.out.println(" got " + b + ", accounts created so far: " + created); }}orElse: creating account for 9876543210 got ACC-3210, accounts created so far: 1 orElseGet: got ACC-3210, accounts created so far: 1
What this code does
- The account exists, yet
orElse(createAccount(...))printscreating accountand increases the counter: the argument is evaluated beforeorElseruns, and its result is thrown away. orElseGet(() -> createAccount(...))passes a lambda instead. The value is present, so the lambda never runs and the counter stays at 1.
For a constant like "Guest" or 0, orElse is fine and clearer. For a database call, a network call, or anything with a side effect, such as creating an account, use orElseGet, which takes a lambda and runs it only when the Optional is empty. Revise: orElse, orElseGet and orElseThrow (opens in a new tab).
Must know:
orElse(expr)always evaluatesexpr(eager).orElseGet(() -> expr)evaluates only when empty (lazy).orElseThrow()(Java 10) isget()with an honest name:NoSuchElementException.orElseThrow(() -> new XException(...))throws your own exception, created only when needed.
Predict the output
orElse or orElseGet?
Read each program and pick what it prints.
Round 1 of 4
A full Optional, with orElse.
Anti-patterns: get() without a check, Optional fields and parameters
An Optional anti-pattern is a use of Optional that adds risk or clutter: get() without a check, Optional.of on a possible null, an Optional field or parameter, or an Optional that wraps a collection.
These habits lose marks in an interview: get() without a check, Optional.of on a value that may be null, Optional fields and parameters, and returning null from an Optional method.
Example 3 · Find the bug: get() on empty and Optional.of(null)
import java.util.Map;import java.util.NoSuchElementException;import java.util.Optional;
public class GetTrapDemo { static Map<String, Integer> coupons = Map.of("FEST20", 20);
public static void main(String[] args) { Optional<Integer> discount = Optional.ofNullable(coupons.get("FEST50")); try { System.out.println("Discount: " + discount.get()); } catch (NoSuchElementException e) { System.out.println("get() on empty: " + e.getMessage()); }
try { Optional<Integer> bad = Optional.of(coupons.get("FEST50")); System.out.println(bad); } catch (NullPointerException e) { System.out.println("Optional.of(null): NullPointerException"); }
int safe = Optional.ofNullable(coupons.get("FEST50")).orElse(0); System.out.println("Fixed: discount " + safe); }}get() on empty: No value present Optional.of(null): NullPointerException Fixed: discount 0
What this code does
get()on an empty Optional throwsNoSuchElementExceptionwith the messageNo value present, the classic "Optional used like null" bug.Optional.of(coupons.get("FEST50"))throwsNullPointerExceptionright away, becauseofrefusesnull.ofNullableplusorElse(0)is the fix.
Example 4 · Anti-pattern: Optional as a parameter, and the overload fix
import java.util.Optional;
public class OptionalParamDemo { // Anti-pattern: Optional as a parameter static int feeWithOptional(int base, Optional<Integer> discount) { return base - discount.orElse(0); }
// Better: two clear overloads static int fee(int base) { return base; }
static int fee(int base, int discount) { return base - discount; }
public static void main(String[] args) { System.out.println(feeWithOptional(500, Optional.of(50))); System.out.println(feeWithOptional(500, Optional.empty())); try { System.out.println(feeWithOptional(500, null)); } catch (NullPointerException e) { System.out.println("Caller passed null: NullPointerException"); }
System.out.println(fee(500, 50)); System.out.println(fee(500)); }}450 500 Caller passed null: NullPointerException 450 500
What this code does
- Callers of
feeWithOptionalmust wrap every argument, and nothing stops them from passingnull, which crashes inside the method. - Two overloads,
fee(int)andfee(int, int), say the same thing with no wrapping and no way to pass anullOptional.
get() throws NoSuchElementException: No value present on an empty Optional. if (opt.isPresent()) { use(opt.get()); } works but is just a null check with extra steps; prefer ifPresent, map or orElse. Optional is not Serializable and adds an object per field, and a parameter can still be passed as null, so keep it for return types. Revise: Optional do's and don'ts (opens in a new tab).
Must know:
Optional.of(null)throwsNullPointerException; useofNullable.- A method returning
Optionalmust returnOptional.empty(), nevernull. - Fields: keep a nullable field and add a getter that returns
Optional.ofNullable(field). - Parameters: use overloads or a default value instead of
Optionalparameters. - Never wrap a collection in Optional; return an empty list instead.
Find the bug
Find the Optional bug
Each snippet should be safe. Tap the wrong line, then check the fix.
Read the domain of a customer's email, if any.
Round 1 of 4map, flatMap, filter and ifPresentOrElse chains
On Optional, map applies a function that returns a plain value and wraps the result. flatMap applies a function that already returns an Optional, so you get Optional<T> and not Optional<Optional<T>>.
A chain replaces nested null checks. Follow one phone number through flatMap, map and orElse to a city name.
Example 5 · flatMap, map, filter and ifPresentOrElse in one chain
import java.util.Map;import java.util.Optional;
public class ChainDemo { record Address(String city) {}
record User(String name, Address address) { Optional<Address> addressOpt() { return Optional.ofNullable(address); } }
static Map<String, User> users = Map.of( "98100", new User("Asha", new Address("Pune")), "98200", new User("Ravi", null), "98300", new User("Meena", new Address(" ")));
static Optional<User> findUser(String phone) { return Optional.ofNullable(users.get(phone)); }
public static void main(String[] args) { for (String phone : new String[] {"98100", "98200", "98300", "98400"}) { findUser(phone) .flatMap(User::addressOpt) .map(Address::city) .filter(city -> !city.isBlank()) .ifPresentOrElse( city -> System.out.println(phone + ": ship to " + city), () -> System.out.println(phone + ": no delivery city")); } }}98100: ship to Pune 98200: no delivery city 98300: no delivery city 98400: no delivery city
What this code does
addressOpt()already returns an Optional, soflatMapis needed;map(Address::city)then works on a plainAddress. Any empty step skips the rest of the chain.filter(city -> !city.isBlank())turns Meena's blank city into empty, andifPresentOrElseprints one line for every case without a singleifornullcheck.
filter(p) keeps the value only if it passes the test. A chain such as findUser(phone).flatMap(User::addressOpt).map(Address::city).orElse("Unknown") replaces three nested null checks. ifPresentOrElse (Java 9) runs one action for a value and another for the empty case, the clean replacement for if (isPresent()) ... else .... Revise: Transforming Optional (opens in a new tab).
Fix the error
Fix the Optional compile errors
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
Get the user's address, which is already an Optional.
Error
FixFlat.java:9: error: incompatible types: inference variable U has incompatible bounds
Optional<Address> a = Optional.of(u).map(User::address);
^
equality constraints: AddressModel answer: should a method return null or Optional?
Interviewers love this question. Here is the spoken answer, then a method that returns an empty list, the safe way to say "no results".
import java.util.List;import java.util.Map;
public class EmptyListSnip { static Map<String, List<String>> orders = Map.of("Asha", List.of("O1", "O2"));
static List<String> ordersOf(String name) { return orders.getOrDefault(name, List.of()); // empty list, not null or Optional }
public static void main(String[] args) { System.out.println(ordersOf("Asha").size() + " " + ordersOf("Ravi").size()); }}2 0
Spoken answer: "If the method finds a single thing that may legitimately be missing, like findByEmail, I return Optional<T>, because the type tells the caller to handle the empty case. If the method returns a collection, I return an empty collection, never null and never Optional<List>. Inside a class, for private fields and performance-critical code, a plain nullable value is fine."
Follow-up they often add: "Is Optional a replacement for null checks everywhere?" No. It is a return-type tool. Spring Data JPA follows the same rule: findById returns Optional<T>, while findAll returns a List.
Next step
Check your understanding
12 quick questions