Skip to lesson

Optional: Correct and Incorrect Use

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

WhyOptionalDemo.javaJava
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());    }}
Output
null version crashed: NullPointerException
ASHA
NOT FOUND
Is 105 present? false

What this code does

  • findNameOrNull(105) returns null, and the crash happens later at n.toUpperCase(), far from the lookup. Nothing in the method's signature warned the caller.
  • findName returns Optional<String>, so the caller writes map(...).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 (from IntStream.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

OrElseTrapDemo.javaJava
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);    }}
Output
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(...)) prints creating account and increases the counter: the argument is evaluated before orElse runs, 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 evaluates expr (eager).
  • orElseGet(() -> expr) evaluates only when empty (lazy).
  • orElseThrow() (Java 10) is get() 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.

import java.util.Optional;
public class OptB {
static String slow() {
System.out.print("slow ");
return "B";
}
public static void main(String[] args) {
System.out.println(Optional.of("A").orElse(slow()));
}
}

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)

GetTrapDemo.javaJava
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);    }}
Output
get() on empty: No value present
Optional.of(null): NullPointerException
Fixed: discount 0

What this code does

  • get() on an empty Optional throws NoSuchElementException with the message No value present, the classic "Optional used like null" bug.
  • Optional.of(coupons.get("FEST50")) throws NullPointerException right away, because of refuses null. ofNullable plus orElse(0) is the fix.

Example 4 · Anti-pattern: Optional as a parameter, and the overload fix

OptionalParamDemo.javaJava
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));    }}
Output
450
500
Caller passed null: NullPointerException
450
500

What this code does

  • Callers of feeWithOptional must wrap every argument, and nothing stops them from passing null, which crashes inside the method.
  • Two overloads, fee(int) and fee(int, int), say the same thing with no wrapping and no way to pass a null Optional.

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) throws NullPointerException; use ofNullable.
  • A method returning Optional must return Optional.empty(), never null.
  • Fields: keep a nullable field and add a getter that returns Optional.ofNullable(field).
  • Parameters: use overloads or a default value instead of Optional parameters.
  • 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 4

map, 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

ChainDemo.javaJava
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"));        }    }}
Output
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, so flatMap is needed; map(Address::city) then works on a plain Address. Any empty step skips the rest of the chain.
  • filter(city -> !city.isBlank()) turns Meena's blank city into empty, and ifPresentOrElse prints one line for every case without a single if or null check.

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.

import java.util.Optional;
public class FixFlat {
record Address(String city) {}
record User(String name, Optional<Address> address) {}
public static void main(String[] args) {
User u = new User("Asha", Optional.of(new Address("Pune")));
Optional<Address> a = Optional.of(u).map(User::address);
System.out.println(a);
}
}

Error

FixFlat.java:9: error: incompatible types: inference variable U has incompatible bounds
        Optional<Address> a = Optional.of(u).map(User::address);
                                                ^
    equality constraints: Address

Model 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".

EmptyListSnip.javaJava
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());    }}
Output
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