Optional was designed as a return type for methods that may legitimately have no result, so the caller cannot ignore absence. It is a poor fit for fields, constructor parameters and method arguments, and it should not wrap a collection, since an empty list already says nothing here. Calling get without checking defeats the purpose; use map, filter, orElseGet or orElseThrow with a meaningful exception.
Why interviewers ask this
It is a small API design question that reveals how you think about nullability and readability. The interviewer wants to see that you know why it exists, that it is not serializable and so does not belong in entities or DTO fields, and that chaining is what makes it valuable. Answers that treat it as a null check wrapper usually come with code that is harder to read than the null was.
How to structure your answer
- State the intended use: a return type expressing possible absence.
- List the places it does not belong and why.
- Show the chaining style instead of isPresent and get.
- Mention the empty collection rule.
Example answer
It exists so a method signature can say this may not return anything, which a nullable return type never communicated. So repository style lookups return an Optional and the caller is forced to deal with it. Where it goes wrong is when people put it everywhere. As a field it adds an object per instance and is not serializable, which causes real problems in entities and payloads. As a parameter it just gives callers three states to think about instead of two, so I use an overload instead. And a method returning a collection returns an empty collection, never an Optional of a list, because empty already means the same thing. Style wise, if I write isPresent followed by get I have just written a null check with extra ceremony, so I chain instead: map to the thing I want, filter, then orElseThrow with a domain exception that says which id was not found. The one thing I would not do is use it as a general purpose null replacement across an existing codebase, since the mixed style is worse than either convention alone.
Walking into this interview soon? GhostPilot listens to your live call, spots the question the moment it is asked, and puts a structured answer on your screen in real time. Try it on your next mock, or grab a $29 Session Pass, no subscription, for the real thing.
See how it worksFollow-up questions to expect
- What is the difference between orElse and orElseGet?
- How would you handle a nullable field that comes from an external API?
- How does Optional interact with streams?
Related java developer questions
Your interviewer will ask their own version of this. Paste your actual job description into the free Question Predictor and get the 20 questions that role is most likely to ask, with what each one is really probing.
Predict my questions