An Optional always contains a non-null value or is empty, yes, but you don't have an Optional, you have a reference of type Optional pointing to null. You need to initialize testString, e.g. to Optional.empty().

Optional isn't magic, it's an object like any other, and the Optional reference itself can be null. It's the contents of the Optional that can't be null.

Answer from Louis Wasserman on Stack Overflow
🌐
Medium
medium.com › javarevisited › java-null-handling-with-optionals-b2ded1f48b39
Java - Null Handling With Optionals | by Ömer Kurular | Javarevisited | Medium
September 4, 2021 - Now, let’s look at methods that check presence of value. isPresent(), returns true if the Optional contains a non-null value and false otherwise.
🌐
Baeldung
baeldung.com › home › java › java optional as return type
Java Optional as Return Type | Baeldung
January 8, 2024 - The Optional type was introduced in Java 8. It provides a clear and explicit way to convey the message that there may not be a value, without using null. When getting an Optional return type, we’re likely to check if the value is missing, ...
🌐
Baeldung
baeldung.com › home › java › core java › guide to java optional
Guide To Java Optional | Baeldung
December 8, 2016 - So, there are solutions to avoid using Optionals as method parameters. 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.
🌐
Reddit
reddit.com › r/java › why does optional require a non-null value?
r/java on Reddit: Why does Optional require a non-null value?
June 13, 2024 -

Since the whole purpose of Optional is to represent values that might not exist, why does the constructor of Optional require a non-null value? Is it becuase they wanted to coalesce all empty Optionals down to a single instance? Even if that's true, why not make Optional.of() behave the way Optional.ofNullable() and do away with the ofNullable() method?

Edit to clarify my opinion and respond to some of the points raised:

My opinion stated clearly, is only two "constructor" methods should exist:

  • of (and it should work like the current ofNullable method)

  • empty

So far the arguments against my opinion have been:

  1. Having .of() and .ofNullable() makes it clear at the point of construction when the value exists and when it might not exist.

This is true, but that clarity is redundant. For safety, the call to .of() will either be inside the not-null branch of a null-check, or come after a not-null assertion. So even if .of() behaved as .ofNullable() does it would be clear that the value exists.

2. It guards against changes in behavior of the the methods supplying the values. If one of the supplying methods suddenly changes from never returning nulls to sometime returning nulls it will catch the error.

I would argue that guarding against this occurrence is the responsibility of the function returning the Optional values, and not the responsibility of Optional. If the function needs to guard against a null value so that it can handle it in some fashion (eg. by calling another supplier method) then then it needs to implement the not-null assertion explicitly in the body of its code. This is more clear than relying on an class called Optional do something that is semantically at odds with the plain reading of its class name.

In the case where the function doesn't care whether the value returned from the supplier is null or not, it should simply be able to call .of() to create the optional and return it.

Top answer
1 of 9
23

Optional harnesses the type system for doing work that you'd otherwise have to do all in your head: remembering whether or not a given reference may be null. This is good. It's always smart to let the compiler handle boring drugework, and reserve human thought for creative, interesting work.

Without Optional, every reference in your code is like an unexploded bomb. Accessing it may do something useful, or else it may terminate your program wth an exception.

With Optional and without null, every access to a normal reference succeeds, and every reference to an Optional succeeds unless it's unset and you failed to check for that. That is a huge win in maintainability.

Unfortunately, most languages that now offer Optional haven't abolished null, so you can only profit from the concept by instituting a strict policy of "absolutely no null, ever". Therefore, Optional in e.g. Java is not as compelling as it should ideally be.

2 of 9
23

An Optional brings stronger typing into operations that may fail, as the other answers have covered, but that is far from the most interesting or valuable thing Optionals bring to the table. Much more useful is the ability to delay or avoid checking for failure, and to easily compose many operations that may fail.

Consider if you had your optional variable from your example code, then you had to perform two additional steps that each might potentially fail. If any step along the way fails, you want to return a default value instead. Using Optionals correctly, you end up with something like this:

return optional.flatMap(x -> x.anotherOptionalStep())
               .flatMap(x -> x.yetAnotherOptionalStep())
               .orElse(defaultValue);

With null I would have had to check three times for null before proceeding, which adds a lot of complexity and maintenance headaches to the code. Optionals have that check built in to the flatMap and orElse functions.

Note I didn't call isPresent once, which you should think of as a code smell when using Optionals. That doesn't necessarily mean you should never use isPresent, just that you should heavily scrutinize any code that does, to see if there is a better way. Otherwise, you're right, you're only getting a marginal type safety benefit over using null.

Also note that I'm not as worried about encapsulating this all into one function, in order to protect other parts of my code from null pointers from intermediate results. If it makes more sense to have my .orElse(defaultValue) in another function for example, I have much fewer qualms about putting it there, and it's much easier to compose the operations between different functions as needed.

🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Optional.html
Optional (Java Platform SE 8 )
October 20, 2025 - Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.
Find elsewhere
🌐
Readthedocs
java8tips.readthedocs.io › en › stable › optional.html
10. Handling nulls with Optional — Java 8 tips 1.0 documentation
The advantage over using this method is if the given value is null then it returns an empty optional and rest of the operations performed on it will be supressed.
🌐
Javapractices
javapractices.com › topic › TopicAction.do
Java Practices->Return Optional not null
The returned Optional object is itself never null! That would completely defeat the purpose of using {@code Optional<T>}. */ public Optional<LocalDate> getBirthDate() { return Optional.ofNullable(birthDate); } /** Debugging only. */ @Override public String toString(){ String SEP = ", "; return name + SEP + address + SEP + friends + SEP + birthDate; } // PRIVATE /** Required. Never empty. Its value will come from somewhere.
🌐
Medium
medium.com › thefreshwrites › java-optional-and-either-handling-null-values-and-representing-two-possible-values-6a477a0fe189
Java Optional and Either: Handling Null Values and Representing Two Possible Values | by Samuel Catalano | Mar, 2023 | Medium | The Fresh Writes
March 10, 2023 - In this example, optionalName is an Optional that contains a value if name is not null, otherwise it is empty. The orElse() method returns the value if it is present, otherwise it returns the default value “Unknown”. Java Either is a class that provides a way to represent one of two possible values.
🌐
Readthedocs
java-8-tips.readthedocs.io › en › stable › optional.html
10. Handling nulls with Optional — Java 8 tips 1.0 documentation
You can create an optional object from a nullable value using the static factoy method Optional.ofNullable. The advantage over using this method is if the given value is null then it returns an empty optional and rest of the operations performed on it will be supressed.
🌐
DZone
dzone.com › coding › languages › 26 reasons why using optional correctly is not optional
26 Reasons Why Using Optional Correctly Is Not Optional
November 28, 2018 - Both are missing the fact that Optional.of(fetch())will throw NPE iffetch()returns null. Moreover, the final code is chaining Optionalmethodsof()andorElse()with the single purpose of returning a value instead of returning based on a simplenullcheck (Item 12). In the end, the code is still prone to NPE. One of the acceptable approaches consists in refactoring thefetch()method to returnOptionaland from the pwd()method to return, fetch().orElse("none"). Hope this helps! Let us know your thoughts in the comments section below. Java (programming language) code style Object (computer science)
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.

🌐
Oracle
oracle.com › java › technical details
Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional!
In this article, we have seen how ... single null reference in your codebase but rather to help design better APIs in which—just by reading the signature of a method—users can tell whether to expect an optional value....
🌐
Medium
medium.com › @reetesh043 › java-optional-avoiding-null-pointer-exceptions-made-easy-d44e34b7c3e1
Java Optional: Avoiding Null Pointer Exceptions Made Easy | by Reetesh Kumar | Medium
February 9, 2024 - Alternatively, we can use the ofNullable() method, which allows us to pass a potentially null value. If the value is null, it will create an empty Optional.
🌐
Medium
devcookies.medium.com › mastering-optional-in-java-the-best-way-to-handle-nulls-29702f8fd295
Mastering Optional in Java: The Best Way to Handle Nulls
March 20, 2025 - To address this issue, Java 8 introduced Optional<T>, a container class that can hold either a non-null value or indicate absence of a value in a safe and explicit way. ... ✅ Prevents NullPointerException — Instead of returning null, Optional<> ensures the absence of a value is handled gracefully...
🌐
Developer.com
developer.com › dzone › coding › java › how to use optionals in java
How to use Optional in Java
June 16, 2020 - A variable whose type is Optional should never itself be null; it should always point to an Optional instance. If a null value is returned in place of an Optional object, this is a breach of the method contract on the part of the method developer.
🌐
Indrek
blog.indrek.io › articles › misusing-java-optional
Misusing Java’s Optional type | That Which Inspires Awe
October 5, 2019 - When you see that a method returns an Optional of something, this is a clear indication that the method signature is trying to tell you that the return value might be missing. The good thing about Optionals is that they force you to handle the special case where there might be no value. Since Optionals are designed so that we don’t have to explicitly deal with null references anymore, returning a null from an Optional-returning method will definitely throw somebody off guard.
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › docs › api › java.base › java › util › Optional.html
Optional (Java SE 17 & JDK 17)
October 20, 2025 - A variable whose type is Optional should never itself be null; it should always point to an Optional instance. ... Returns an empty Optional instance. ... Indicates whether some other object is "equal to" this Optional. ... If a value is present, and the value matches the given predicate, returns ...