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
🌐
Baeldung
baeldung.com › home › java › core java › guide to java optional
Guide To Java Optional | Baeldung
December 8, 2016 - In the above example, we wrap a null text inside an Optional object and attempt to get the wrapped value using each of the two approaches.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Optional.html
Optional (Java Platform SE 8 )
October 20, 2025 - If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional. ... This method supports post-processing on optional values, without the need to explicitly check for a return status. For example, the following code traverses a stream of file names, selects one that has not yet been processed, and then opens that file, returning an Optional<FileInputStream>:
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.

🌐
Readthedocs
java8tips.readthedocs.io › en › stable › optional.html
10. Handling nulls with Optional — Java 8 tips 1.0 documentation
null: 200d; } Here the map method is called inside flatMap just for the availability of framework value to invoke reimburse. Originally reimbursement will be executed by map method and flatMap will just return calculated result. ... If the value matches the given predicate, then the Optional ...
🌐
Baeldung
baeldung.com › home › java › java optional as return type
Java Optional as Return Type | Baeldung
January 8, 2024 - On the other hand, we’ve also learned that there are many scenarios that we would be better off to not use Optional return type for a getter. While we can use Optional type as a hint that there might be no non-null value, we should be careful not to overuse the Optional return type, particularly in a getter of an entity bean or a DTO.
🌐
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.
🌐
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.
Find elsewhere
🌐
Medium
medium.com › javarevisited › java-null-handling-with-optionals-b2ded1f48b39
Java - Null Handling With Optionals | by Ömer Kurular | Javarevisited | Medium
September 4, 2021 - For example, for the findByUsername method, we pass username and it returns related user from database. But, such user may not exist. In this case, we better return User wrapped inside Optional to handle nulls better.
🌐
Javapractices
javapractices.com › topic › TopicAction.do
Java Practices->Return Optional not null
When the return type of a method is Optional<T>, then the caller is forced into explicitly handling the null case. Example · In the example below, the class has a private LocalDate that holds a birth date. It has no "empty" default value. The getBirthDate method returns an Optional<LocalDate> ...
🌐
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.

🌐
Developer.com
developer.com › dzone › coding › java › how to use optionals in java
How to use Optional in Java
June 16, 2020 - For example, if a conversion from a given object to another is not possible, then the map method should return an empty Optional. An anti-pattern for performing this technique is to have the Function object return null, which will then be wrapped ...
🌐
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 - Starting with Java 11, we can easily return atrueif anOptionalis empty via theisEmpty()method. ... // AVOID (Java 11+) public Optional<String> fetchCartItems(long id) { Cart cart = ... ; // this may be null ...
🌐
Foojay
foojay.io › home › optional in java: a swiss army knife for handling nulls and improving code quality
Optional in Java: A Swiss Army Knife for Handling Nulls and Improving Code Quality
February 20, 2023 - In this example, we create an Optional from a potentially null value, and use Optional.map() to perform a transformation on the value only if it is present. This avoids the need for an if statement to check for null, and makes the code more concise and readable. Optional can be used to compose methods together more concisely and expressively. By wrapping the return value of a method in an Optional, you can use Optional methods to chain multiple methods calls together.
🌐
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 - ✅ Improves Code Readability – Clearly conveys that a method may not return a value. ✅ Encourages Functional Programming – Provides useful methods like ifPresent(), orElse(), map(), and flatMap() to operate on values safely. import java.util.Optional;public class OptionalExample { public static void main(String[] args) { // Creating an Optional with a non-null value Optional<String> optionalName = Optional.of("John"); // Creating an empty Optional Optional<String> emptyOptional = Optional.empty(); // Creating an Optional that might be null Optional<String> nullableOptional = Optional.ofNullable(null); } }
🌐
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 - If the mapping function returns a null result then this method returns an empty Optional. ... This method supports post-processing on Optional values, without the need to explicitly check for a return status. For example, the following code traverses a stream of URIs, selects one that has not yet been processed, and creates a path from that URI, returning an Optional<Path>:
🌐
A N M Bazlur Rahman
bazlur.ca › home › optional in java: a swiss army knife for handling nulls and improving code quality
Optional in Java: A Swiss Army Knife for Handling Nulls and Improving Code Quality
February 27, 2023 - In this example, we create an Optional from a potentially null value, and use Optional.map() to perform a transformation on the value only if it is present. This avoids the need for an if statement to check for null, and makes the code more concise and readable. Optional can be used to compose methods together more concisely and expressively. By wrapping the return value of a method in an Optional, you can use Optional methods to chain multiple methods calls together.
🌐
Laulem
laulem.com › en › dev › optional-usage-java-tutorial.html
Guide To Java Optional - LauLem.com
Example: // non-null element Optional<String> myOptional = Optional.ofNullable("Alex"); System.out.println(myOptional.get()); // Alex // null element Optional<String> myOptional2 = Optional.ofNullable(null); System.out.println(myOptional2.get()); // Exception in thread "main" java.util.NoS...
🌐
Medium
medium.com › javarevisited › junior-devs-return-null-senior-devs-use-these-4-optional-patterns-in-java-bb56894c174a
Junior Devs Return null. Senior Devs Use These 4 Optional Patterns in Java | by HabibWahid | Javarevisited | Feb, 2026 | Medium
1 week ago - In this article, I’ll show you the four Optional patterns that eliminate hidden null traps — and instantly make your Java code look senior-level in code reviews. ... public class UserService { @Autowired private UserRepository userRepository; public User findById(Long id) { return userRepository.findById(id).orElse(null); // 💣 } public String getUserEmail(Long id) { User user = findById(id); return user.getEmail(); // NullPointerException waiting to happen } }
🌐
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 - If the mapping function returns a null result then this method returns an empty Optional. ... This method supports post-processing on Optional values, without the need to explicitly check for a return status. For example, the following code traverses a stream of URIs, selects one that has not yet been processed, and creates a path from that URI, returning an Optional<Path>: