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
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-8-optional-class
Java 8 Optional Class - GeeksforGeeks
May 16, 2026 - To avoid abnormal termination, we use the Optional class. In the following example, we are using Optional. So, our program can execute without crashing. ... import java.util.Optional; // Driver Class public class OptionalDemo { // Main Method public static void main(String[] args) { String[] words = new String[10]; Optional<String> checkNull = Optional.ofNullable(words[5]); if (checkNull.isPresent()) { String word = words[5].toLowerCase(); System.out.print(word); } else System.out.println("word is null"); } }
🌐
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, invoke the specified consumer with the value, otherwise do nothing. ... If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional.
Discussions

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
java - Uses for Optional - Stack Overflow
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"). ... Another disadvantage (or limitation) is that you cannot sort Optional(xxx) instances, though Oracle clearly imposed that restriction deliberately. I'm skeptical about the wisdom of having these classes ... More on stackoverflow.com
🌐 stackoverflow.com
Pattern match Optional in Java 21
The wrapper to convert an optional into a list just so you can use for is literally the dumbest thing I have seen someone do in such a long time. More on reddit.com
🌐 r/java
53
40
February 20, 2024
Implementing optional JSON fields in System.Text.Json serialization
Interesting choice to go with a new Optional type instead of using Nullable and using a [Required] attribute for reference types that aren't optional. More on reddit.com
🌐 r/csharp
6
61
June 8, 2021
🌐
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 is a part of the java.util 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 ). The Optional class is an implementation of the Null Object pattern, which ...
🌐
Baeldung
baeldung.com › home › java › core java › guide to java optional
Guide To Java Optional | Baeldung
February 15, 2026 - The intent of Java when releasing Optional was to use it as a return type, thus indicating that a method could return an empty value. As a matter of fact, the practice of using Optional as a method parameter is even discouraged by some code inspectors. As discussed above, Optional is meant to be used as a return type. Trying to use it as a field type is not recommended. Additionally, using Optional in a serializable class will result in a NotSerializableException.
🌐
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.
🌐
Tutorialspoint
tutorialspoint.com › java › java_optional_class.htm
Java - Optional Class
This class acts as a wrapper over the value. Apart from handling null value, Optional class provides lots of utility methods like getting a default value in case of null value, throwing exception in case underlying value is null.
🌐
Scaler
scaler.com › home › topics › optional class in java
Optional Class in Java - Scaler Topics
October 17, 2022 - Optional allows you to store the information about presence or absence of values. Optional is a wrapper or container class in Java 8, included in the java.util package, that encapsulates an alternative value.
Find elsewhere
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").

🌐
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.
🌐
JavaTechOnline
javatechonline.com › home › optional class in java 8 – a comprehensive tutorial
Optional Class In Java 8 - A Comprehensive Tutorial - JavaTechOnline
November 5, 2025 - The Optional is a class of the ‘java.util’ package. In simple words, Optional is a single-value container/wrapper that either contains a value or doesn’t. If it doesn’t contain a value, then it is called empty. It was introduced as a wrapper to hold potentially nullable values.
🌐
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 …
🌐
Educative
educative.io › answers › what-is-the-optional-class-in-java
What is the ​optional class in Java?
The Optional class in Java is a container that can hold, at max, one value and gracefully deals with null values.
🌐
Medium
medium.com › @iamvivekojha › optional-class-in-java-everything-you-need-to-know-to-565454184248
Optional class in Java: Everything You Need To Know To Get Started | by Vivek Ojha | Medium
February 12, 2024 - Optional class in Java: Everything You Need To Know To Get Started Optional is a Java class located in the java.util package. That means we can use it anywhere in our Java code, simply by creating an …
🌐
Baeldung
baeldung.com › home › java › core java › uses for optional in java
Uses for Optional in Java | Baeldung
January 8, 2024 - Technically, an Optional is a wrapper class for a generic type T, where the Optional instance is empty if T is null. Otherwise, it’s full. As per the Java 11 documentation, the purpose of Optional is to provide a return type that can represent ...
🌐
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.
🌐
DZone
dzone.com › coding › java › how to use optionals in java
How to Use Optionals in Java
June 16, 2020 - Instead, we need a mechanism that ... Kit (JDK) 7 in the form of the Optional class. This class acts as a wrapper for an object that may not be present....
🌐
Stackify
stackify.com › optional-java
Understanding, Accepting and Leverage Optional in Java- Stackify
June 27, 2024 - Optional is a useful addition to the Java language, intended to minimize the number of NullPointerExceptions in your code, though not able to completely remove them. It’s also a well designed and very natural addition to the new functional ...
🌐
DEV Community
dev.to › codegreen › optional-class-in-java-and-its-methods-29ap
Optional Class in Java and its methods - DEV Community
November 16, 2024 - The Optional class in Java is a container object that may or may not contain a non-null value.
🌐
JavaGoal
javagoal.com › home › optional class in java 8
Optional class in java and how to use it - JavaGoal
July 15, 2022 - Optional is a generic class in java, so you must specify the type of data that can it hold. The Optional class provides a way, to replace the null reference of T Type with a non-null value.
🌐
Medium
medium.com › @pratik.941 › mastering-optional-in-java-8-a-comprehensive-guide-3131eac600dc
Mastering optional in Java 8: A Comprehensive Guide | by Pratik T | Medium
May 30, 2024 - Optional in Java 8 is a container class that helps avoid null references and null pointer exceptions. It is used to represent a value that may or may not be present.