The main design goal of Optional is to provide a means for a function returning a value to indicate the absence of a return value. See this discussion. This allows the caller to continue a chain of fluent method calls.

This most closely matches use case #1 in the OP's question. Although, absence of a value is a more precise formulation than null since something like IntStream.findFirst could never return null.


For use case #2, passing an optional argument to a method, this could be made to work, but it's rather clumsy. Suppose you have a method that takes a string followed by an optional second string. Accepting an Optional as the second arg would result in code like this:

foo("bar", Optional.of("baz"));
foo("bar", Optional.empty());

Even accepting null is nicer:

foo("bar", "baz");
foo("bar", null);

Probably the best is to have an overloaded method that accepts a single string argument and provides a default for the second:

foo("bar", "baz");
foo("bar");

This does have limitations, but it's much nicer than either of the above.

Use cases #3 and #4, having an Optional in a class field or in a data structure, is considered a misuse of the API. First, it goes against the main design goal of Optional as stated at the top. Second, it doesn't add any value.

There are three ways to deal with the absence of a value in an Optional: to provide a substitute value, to call a function to provide a substitute value, or to throw an exception. If you're storing into a field, you'd do this at initialization or assignment time. If you're adding values into a list, as the OP mentioned, you have the additional choice of simply not adding the value, thereby "flattening" out absent values.

I'm sure somebody could come up with some contrived cases where they really want to store an Optional in a field or a collection, but in general, it is best to avoid doing this.

Answer from Stuart Marks on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Optional.html
Optional (Java Platform SE 8 )
April 21, 2026 - If a value is present the result must include its string representation in the result. Empty and present Optionals must be unambiguously differentiable. ... Java™ Platform Standard Ed.
🌐
Baeldung
baeldung.com › home › java › core java › guide to java optional
Guide To Java Optional | Baeldung
February 15, 2026 - Optional makes us deal with nullable values explicitly as a way of enforcing good programming practices. Let’s now look at how the above code could be refactored in Java 8.
Discussions

[Discussion] Java Optional outside of a functional context?
Here we go again, 10 years later. Optional is a potentially empty object holder with QoL methods. Use it when you need a potentially empty object holder with QoL methods. More on reddit.com
🌐 r/java
121
55
July 20, 2025
Optional Class in Java – A Comprehensive Tutorial
To be fair, i didnt read the whole article but i find the "best practices" and "Common pitfalls" sections to be lack luster. The "overuse of optional" and "use optional only when necessary" seam kind of obvious but its good to write it out. You shouldn't use optional values when the value isn't actually optional. "Avoid Using Optional in Fields or Parameters" why? I heard a senior of mine say a similar thing before and i didn't understand it then and still don't understand it now. Especially since doing exactly that in rust is not only fine but very common. "Returning Optional from Collections" this one i don't understand at all. Collections in Java are already defined interfaces and you couldn't make the `.get()` method return an option if you wanted to. So if im not implementing an existing collections interface, why shouldn't i return an option for those? The big issue for me is that optionals in java are not null safe. A method that returns an optional might not return a value at all but return null instead. So i *should* do a null check for that. Then i use the optional to check if the value is there or not. And then the value inside of the optional might also be null which i should do a null check on. So really if a method returns an optional i *should* check three times if the value is actually there or not. If it had just returned the value i only need to do one null check. Yes there are best practices to make sure that a variable of type Optional is never null. A method that returns optional should never return null and to never put null into an optional but man would it be nice if the language could just guarantee that from the start. More on reddit.com
🌐 r/programming
12
6
October 17, 2024
Optional vs. null. What is the purpose of Optional in Java 8? - Stack Overflow
In Java 8 you can return an Optional instead of a null. Java 8 documentation says that an Optional is "A container object which may or may not contain a non-null value. If a value is present, isPr... More on stackoverflow.com
🌐 stackoverflow.com
Using the Optional class as it's meant to be used
12 recipes but no mention of map or flatMap. Embrace the monad! More on reddit.com
🌐 r/java
113
136
June 23, 2020
Top answer
1 of 14
299

The main design goal of Optional is to provide a means for a function returning a value to indicate the absence of a return value. See this discussion. This allows the caller to continue a chain of fluent method calls.

This most closely matches use case #1 in the OP's question. Although, absence of a value is a more precise formulation than null since something like IntStream.findFirst could never return null.


For use case #2, passing an optional argument to a method, this could be made to work, but it's rather clumsy. Suppose you have a method that takes a string followed by an optional second string. Accepting an Optional as the second arg would result in code like this:

foo("bar", Optional.of("baz"));
foo("bar", Optional.empty());

Even accepting null is nicer:

foo("bar", "baz");
foo("bar", null);

Probably the best is to have an overloaded method that accepts a single string argument and provides a default for the second:

foo("bar", "baz");
foo("bar");

This does have limitations, but it's much nicer than either of the above.

Use cases #3 and #4, having an Optional in a class field or in a data structure, is considered a misuse of the API. First, it goes against the main design goal of Optional as stated at the top. Second, it doesn't add any value.

There are three ways to deal with the absence of a value in an Optional: to provide a substitute value, to call a function to provide a substitute value, or to throw an exception. If you're storing into a field, you'd do this at initialization or assignment time. If you're adding values into a list, as the OP mentioned, you have the additional choice of simply not adding the value, thereby "flattening" out absent values.

I'm sure somebody could come up with some contrived cases where they really want to store an Optional in a field or a collection, but in general, it is best to avoid doing this.

2 of 14
139

I'm late to the game but for what it's worth, I want to add my 2 Cents. They go against the design goal of Optional, which is well summarized by Stuart Marks's answer, but I'm still convinced of their validity (obviously).

Use Optional Everywhere

In General

I wrote an entire blog post about using Optional but it basically comes down to this:

  • design your classes to avoid optionality wherever feasibly possible
  • in all remaining cases, the default should be to use Optional instead of null
  • possibly make exceptions for:
    • local variables
    • return values and arguments to private methods
    • performance critical code blocks (no guesses, use a profiler)

The first two exceptions can reduce the perceived overhead of wrapping and unwrapping references in Optional. They are chosen such that a null can never legally pass a boundary from one instance into another.

Note that this will almost never allow Optionals in collections which is almost as bad as nulls. Just don't do it. ;)

Regarding your questions

  1. Yes.
  2. If overloading is no option, yes.
  3. If other approaches (subclassing, decorating, ...) are no option, yes.
  4. Please no!

Advantages

Doing this reduces the presence of nulls in your code base, although it does not eradicate them. But that is not even the main point. There are other important advantages:

Clarifies Intent

Using Optional clearly expresses that the variable is, well, optional. Any reader of your code or consumer of your API will be beaten over the head with the fact that there might be nothing there and that a check is necessary before accessing the value.

Removes Uncertainty

Without Optional the meaning of a null occurrence is unclear. It could be a legal representation of a state (see Map.get) or an implementation error like a missing or failed initialization.

This changes dramatically with the persistent use of Optional. Here, already the occurrence of null signifies the presence of a bug. (Because if the value were allowed to be missing, an Optional would have been used.) This makes debugging a null pointer exception much easier as the question of the meaning of this null is already answered.

More Null Checks

Now that nothing can be null anymore, this can be enforced everywhere. Whether with annotations, assertions or plain checks, you never have to think about whether this argument or that return type can be null. It can't!

Disadvantages

Of course, there is no silver bullet...

Performance

Wrapping values (especially primitives) into an extra instance can degrade performance. In tight loops this might become noticeable or even worse.

Note that the compiler might be able to circumvent the extra reference for short lived lifetimes of Optionals. In Java 10 value types might further reduce or remove the penalty.

Serialization

Optional is not serializable but a workaround is not overly complicated.

Invariance

Due to the invariance of generic types in Java, certain operations become cumbersome when the actual value type is pushed into a generic type argument. An example is given here (see "Parametric polymorphism").

🌐
GeeksforGeeks
geeksforgeeks.org › java › java-8-optional-class
Java 8 Optional Class - GeeksforGeeks
May 16, 2026 - Java 8 introduced the Optional class to handle null values safely. It is a container object that may or may not contain a value.
🌐
Reddit
reddit.com › r/java › [discussion] java optional outside of a functional context?
r/java on Reddit: [Discussion] Java Optional outside of a functional context?
July 20, 2025 -

Optional was introduced back in JDK8 (seems like yesterday to me), as a way to facilitate functional control on empty responses from method calls, without having to deal with explicit null checks.

Since then Optional has been used in a variety of other contexts, and there are some guidelines on when to use them. These guidelines although are disregarded for other patterns, that are used in popular libraries like Spring Data JPA.

As the guidance says you shouldn't "really" be using Optional outside of a stream etc.

Here is an example that goes against that guidance from a JPA repository method.

e.g. (A repository method returning an optional result from a DB)

public static Optional<User> findUserByName(String name) {
    User user = usersByName.get(name);
    Optional<User> opt = Optional.ofNullable(user);
    return opt;
}

There are some hard no's when using Optional, like as properties in a class or arguments in a method. Fair enough, I get those, but for the example above. What do you think?

Personally - I think using Optional in APIs is a good thing, the original thinking of Optional is too outdated now, and the usecases have expanded and evolved.

🌐
Medium
medium.com › @alxkm › optional-in-java-best-practices-for-safer-code-3f4a3b80e122
Optional in Java: Best Practices for Safer Code. Java Interview | by Alex Klimenko | Medium
August 9, 2025 - Optional in Java: Best Practices for Safer Code. Java Interview Introduced in Java 8, Optional is a container object used to represent the presence or absence of a value. It was designed to help …
Find elsewhere
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › util › Optional.html
Optional (Java SE 11 & JDK 11 )
January 20, 2026 - Optional is primarily intended for use as a method return type where there is a clear need to represent "no result," and where using null is likely to cause errors.
🌐
Reddit
reddit.com › r/programming › optional class in java – a comprehensive tutorial
r/programming on Reddit: Optional Class in Java – A Comprehensive Tutorial
October 17, 2024 - The big issue for me is that optionals in java are not null safe. A method that returns an optional might not return a value at all but return null instead. So i *should* do a null check for that. Then i use the optional to check if the value is there or not.
🌐
Medium
medium.com › javarevisited › optional-class-in-java-8-making-your-code-more-clear-and-concise-62af0712910d
Optional Class in Java 8: Making Your Code More Clear and Concise . | by Hamza Nassour | Javarevisited | Medium
May 29, 2024 - It was introduced as a way to help ... package and was added to Java as part of Java 8. Optional is a container that either contains a non-null value or nothing(empty Optional )....
🌐
Frontend Masters
frontendmasters.com › blog › java-optionals
Java Optionals – Master.dev Blog
August 30, 2024 - The post discusses the drawbacks of null references in programming and introduces the Optional type as a solution, particularly in Java. The Optional type helps avoid null reference exceptions by allowing safe interaction with absent values using methods like ifPresent, ifPresentOrElse, map, ...
🌐
DEV Community
dev.to › ivangavlik › how-to-use-the-optional-class-java-3pf5
How to use Optional class (Java) - best practices - DEV Community
January 27, 2024 - It is important to note that the intention of the Optional class is not to replace every single null reference. Instead, its purpose is to help design more-comprehensible APIs so that by just reading the signature of a method, you can tell whether you can expect an optional value.
🌐
Oracle
docs.oracle.com › en › java › javase › 21 › docs › api › java.base › java › util › class-use › Optional.html
Uses of Class java.util.Optional (Java SE 21 & JDK 21)
January 20, 2026 - Returns an Optional containing the nominal descriptor for this instance, if one can be constructed, or an empty Optional if one cannot be constructed. ... Returns a slice of this segment that is the overlap between this and the provided segment. ... Returns the address of the symbol with the given name. ... Returns the Java object stored in the on-heap region of memory backing this memory segment, if any.
Top answer
1 of 3
63

In practice, why is this useful?

For example let's say you have this stream of integers and you're doing a filtering:

int x = IntStream.of(1, -3, 5)
                 .filter(x -> x % 2 == 0)
                 .findFirst(); //hypothetical assuming that there's no Optional in the API

You don't know in advance that the filter operation will remove all the values in the Stream.

Assume that there would be no Optional in the API. In this case, what should findFirst return?

The only possible way would be to throw an exception such as NoSuchElementException, which is IMO rather annoying, as I don't think it should stop the execution of your program (or you'd have to catch the exception, not very convenient either) and the filtering criteria could be more complex than that.

With the use of Optional, it's up to the caller to check whether the Optional is empty or not (i.e if your computation resulted in a value or not).

With reference type, you could also return null (but null could be a possible value in the case you filter only null values; so we're back to the exception case).

Concerning non-stream usages, in addition to prevent NPE, I think it also helps to design a more explicit API saying that the value may be present or not. For example consider this class:

class Car {
   RadioCar radioCar; //may be null or not 
   public Optional<RadioCar> getRadioCar() {
        return Optional.ofNullable(radioCar);
   }
}

Here you are clearly saying to the caller that the radio in the car is optional, it might be or not there.

2 of 3
32

When Java was first designed it was common practice to use a special value, usually called null to indicate special circumstances like I couldn't find what you were looking for. This practice was adopted by Java.

Since then it has been suggested that this practice should be considered an anti-pattern, especially for objects, because it means that you have to litter your code with null checks to achieve reliability and stability. It is also a pain when you want to put null into a collection for example.

The modern attitude is to use a special object that may or may not hold a value. This way you can safely create one and just not fill it with anything. Here you are seeing Java 8 encouraging this best-practice by providing an Optional object.

🌐
Medium
medium.com › @uvrajanshuman › optional-in-java-8-ffcf45e01602
Optional in Java 8. Optional is a generic class defined in… | by Anshuman Yuvraj | Medium
October 2, 2023 - Optional in Java 8 Optional is a generic class defined in the java.util package, that got introduced in Java 8. It facilitates the handling of potentially absent values in a more concise and …
🌐
DEV Community
dev.to › sohailshah › using-optionals-in-java-the-right-way-4aho
Using Optional in Java the right way - DEV Community
August 21, 2023 - The java.util.Optional class is a generic type class that contains only one value of type T. Its purpose is to provide a safer alternative to reference objects of a type T that can be null.
🌐
Javacodehouse
javacodehouse.com › blog › java-optional-use
Java Optional | How and When to use it
January 4, 2024 - Optional is a powerful tool for expressing optional values more clearly and avoiding null pointer exceptions. However, it should be used judiciously, and developers should be mindful of its appropriate application to avoid unnecessary complexity in the code. Tired of Null Pointer Exceptions? Consider Using Java SE 8’s Optional!
🌐
DZone
dzone.com › coding › languages › java optional objects
Java Optional Objects
April 17, 2013 - As you can see, option is a data type with two constructors, one of them stores nothing (i.e. NONE) whereas the other is capable of storing a polymorphic value of some value type 'a (where 'a is just a placeholder for the actual type). Under this model, the piece of code we wrote before in Java, to find a fruit by its name, could be rewritten in SML as follows:
🌐
Code Like A Girl
code.likeagirl.io › java-8-optional-class-cde70f787c35
Java 8 Optional Class. Introduction | by Daily Debug | Code Like A Girl
December 19, 2024 - Optional in Java is a great way to handle optional values explicitly, avoiding null-related issues and making your code more robust and readable.
🌐
Baeldung
baeldung.com › home › java › core java › java optional as return type
Java Optional as Return Type | Baeldung
February 26, 2026 - Learn the best practices and when to return the Optional type in Java.