Quick revision
The short answer
A method that returns a collection should return an empty collection, never null, so callers can simply iterate. A method whose single result may be absent should return Optional, and callers should use orElse, orElseThrow, map or ifPresent rather than calling get() unchecked. Optional is meant for return values only: not for fields, not for parameters, and never wrapped around a collection, where an empty collection already says 'nothing'. For primitives, OptionalInt, OptionalLong and OptionalDouble avoid boxing.
What to remember
In this answer, we saw that returning null hides absence from the signature. For collections we return an empty collection, which callers can iterate safely. For a single result that may be missing we return Optional and consume it with map, orElse, orElseGet, orElseThrow or ifPresent instead of an unchecked get(). We keep Optional out of fields, parameters and collections, where it adds cost and confusion, and we use OptionalInt and its siblings for primitive results.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A method that returns a collection should return an empty collection, never null, so callers can simply iterate. A method whose single result may be absent should return Optional, and callers should use orElse, orElseThrow, map or ifPresent rather than calling get() unchecked. Optional is meant for return values only: not for fields, not for parameters, and never wrapped around a collection, where an empty collection already says 'nothing'. For primitives, OptionalInt, OptionalLong and OptionalDouble avoid boxing.
Why this question is asked
NullPointerException is still one of the most common failures in Java services, and a large share of them come from one method returning null and another forgetting to check. Optional and empty collections are the tools Java gives us to make absence explicit in the method signature. But Optional is also widely misused: as fields, as parameters, wrapped around lists, or unwrapped with get() as if it were a null check in disguise. Interviewers ask this to see whether we know the guidelines and the reasons behind them. In this answer, we will recap why null returns are dangerous, look at collections first, then Optional for single values, how to consume it safely, where it does not belong, and the primitive variants.
1A Quick Recap: Why Returning null Hurts
When a method returns null to mean 'nothing', the signature does not say so. List<Order> findOrders(customerId) looks like it always returns a list. Every caller must remember, from documentation or experience, that it might not, and the one caller that forgets fails with a NullPointerException, often far from where the null came from.
The guidelines below have one shared idea: make absence part of the type, or make it impossible, so the compiler and the reader can see it without reading the implementation.
| Situation | Do | Avoid |
|---|---|---|
| Method returns many results | return an empty collection | return null |
| Method returns one result that may be missing | return Optional<T> | return null |
| Consuming an Optional | map, orElse, orElseThrow, ifPresent | get() without a check |
| Field or parameter that may be missing | nullable field, overloads, or a default | Optional field or parameter |
| Possibly empty collection result | empty List or Set | Optional<List<T>> |
| Missing int, long or double | OptionalInt, OptionalLong, OptionalDouble | Optional<Integer> |
2Return Empty Collections, Not null
For collections, the absence of results already has a perfect representation: an empty collection. Returning it lets every caller use the same code for zero, one or many results.
Notice that the caller code did not change at all; it just stopped crashing. When we build the empty value ourselves, List.of() or Collections.emptyList() return a shared immutable instance, so there is no allocation cost worth worrying about. Some people return null 'to save memory', but an empty immutable list is a single shared object.
3Optional for a Single Result That May Be Missing
Optional<T> was added in Java 8 for exactly one purpose: a return type for methods that may have no result. It is a small container that holds either one value or nothing, and the signature itself tells the caller to handle the empty case. Spring Data's findById is the familiar example.
Each style fits a different need. map transforms the value if present, orElse gives a default, orElseThrow turns absence into an error with a meaningful message, and ifPresent runs an action only when there is a value. The code reads as a description of what should happen in both cases.
4Do Not Call get() Without Checking
Optional.get() returns the value or throws NoSuchElementException if there is none. Calling it without checking simply swaps one runtime exception for another, and it hides the intent.
Java 10 added a no-argument orElseThrow() as the preferred name for get(), because it says what happens. The orElse versus orElseGet difference is a common subtle bug: orElse evaluates its argument eagerly, so a default that calls a database or creates an object runs every time. For anything more than a constant, orElseGet is the right choice.
5Where Optional Does Not Belong
Optional was designed as a return type, and using it elsewhere costs more than it gives. As a field, it adds an extra object per instance, it is not Serializable, and JPA does not map Optional fields, so entities and DTOs should keep nullable fields and offer a getter that returns Optional if that helps callers. As a method parameter, it forces every caller to wrap values, and it gives three states instead of two, since the Optional itself can be null; overloads or a nullable parameter with clear documentation are simpler.
Optional of a collection is the clearest anti-pattern. Optional<List<Order>> has two ways to say 'nothing', an empty Optional and an empty list, and callers must handle both. Since the empty list already expresses absence, we return List<Order>. The same applies to Optional of an array, a Stream or a Map.
6Primitive Optionals Avoid Boxing
For primitive results, Java provides OptionalInt, OptionalLong and OptionalDouble. They hold the primitive directly instead of a boxed Integer, Long or Double. The streams API uses them for results that may not exist.
The primitive variants have a smaller API, without map or filter, so code that needs a rich chain sometimes uses Optional<Integer> anyway. That is acceptable; the rule is about avoiding needless boxing in common paths, not a ban.
7Follow-up questions
Should getters on entities return Optional?
It can help for genuinely optional associations, as long as the field itself stays a plain nullable reference so JPA and serialisers work. For example, a private Address shippingAddress field with a getter Optional<Address> shippingAddress() makes the absence visible to callers. Many teams keep plain getters on entities and use Optional only on repository and service methods; consistency within a codebase matters most.
Is Optional slower than returning null?
It allocates a small object when a value is present, which is cheap and often removed entirely by the JIT through escape analysis. In ordinary service code the difference is invisible next to IO. In very hot loops over primitives, the primitive variants or a sentinel value can be justified, but that is a measured exception.
What about Optional.ofNullable versus Optional.of?
Optional.of(value) throws NullPointerException if value is null, so it is for values we know are present. Optional.ofNullable(value) returns an empty Optional for null, which is how we adapt legacy APIs that return null. Using of() on a value that may be null just moves the crash.
8Conclusion
In this answer, we saw that returning null hides absence from the signature. For collections we return an empty collection, which callers can iterate safely. For a single result that may be missing we return Optional and consume it with map, orElse, orElseGet, orElseThrow or ifPresent instead of an unchecked get(). We keep Optional out of fields, parameters and collections, where it adds cost and confusion, and we use OptionalInt and its siblings for primitive results.
Open with
My guidelines follow from one idea: absence should be visible in the signature or impossible. For methods that return collections, I always return an empty collection instead of null, because then callers can just iterate or stream, and zero results need no special code; List.of() is a shared immutable instance, so there's no real cost.
Then, if they want more
For a method that returns a single value that might not exist, like findByEmail, I return Optional, which is what it was designed for. When consuming it, I avoid calling get without a check, because that just swaps a NullPointerException for NoSuchElementException.
Instead I use map to transform, orElse for a constant default, orElseGet when the default is expensive because orElse is evaluated eagerly, orElseThrow with my own exception when absence is an error, and ifPresent for side effects.
I don't use Optional for fields, because it isn't Serializable, JPA doesn't map it, and it adds an object per instance; nor for parameters, because callers have to wrap values and the Optional itself could be null.
And I never return Optional of a list, because an empty list already means nothing, so the caller would have two empty cases to handle. For primitives, I use OptionalInt, OptionalLong and OptionalDouble, like IntStream.max returns, to avoid boxing.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 10, Java 8
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "What guidelines do you follow for Optional and for returning collections from methods?...": https://scrivio-interview-library.netlify.app/java/clean-code/99cf5cc5c6/