Java · OOP, JVM and backend craft
What is Optional and when should you use it?
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.
public Optional<User> findById(long id) {
return Optional.ofNullable(repository.find(id));
}
String name = findById(42)
.map(User::name)
.orElse("unknown");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.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why should Optional not be used for fields?
- 2What is the difference between orElse and orElseGet?
- 3When should you use orElseThrow?
- 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.