Java · OOP, JVM and backend craft

What is Optional and when should you use it?

Mediumoptionalnull safetyapi designUpdated Oct 2026
Quiz this track

Short answer

Optional is a container that explicitly represents a value that may be absent. It is intended mainly for return types, not fields, parameters or collection elements.

Optional makes absence part of the type instead of an undocumented null. It forces callers to make a decision: provide a default, map the value, throw a clear exception or handle emptiness. It is a return-type tool, not a general null replacement.

java
public Optional<User> findById(long id) {
    return Optional.ofNullable(repository.find(id));
}

String name = findById(42)
    .map(User::name)
    .orElse("unknown");
map transforms only when a value is present. orElse supplies a fallback.

Practical rules

  • Return Optional from lookup methods that may legitimately find nothing
  • Do not use it for fields, method parameters or collection elements
  • Use orElseGet for an expensive fallback and orElse for a cheap constant
  • Avoid Optional.get unless presence was already checked
  • Use orElseThrow with a meaningful exception for missing required data

Optional is not serializable by design and adds allocation. In hot paths or entity fields it can be worse than a nullable reference. For a collection, return an empty collection instead of Optional of a collection, because empty and absent are the same thing in that context.

orElse evaluates its argument eagerly even when a value is present. orElseGet takes a supplier and only runs when needed.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Why should Optional not be used for fields?
  2. 2What is the difference between orElse and orElseGet?
  3. 3When should you use orElseThrow?
  4. 4Why is Optional not serializable?

Say it in the interview

Optional makes the possibility of absence explicit in a method's return type. I use it for lookups that may find nothing, and I compose with map, filter and orElseThrow instead of returning null. I avoid it for fields, parameters and collection elements, where it adds noise. I also use orElseGet when the fallback is expensive, since orElse evaluates eagerly.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Java mock interview and get scored feedback on depth, clarity and confidence.