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.

Answer from Alex on Stack Overflow
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.

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.

Discussions

Why does Optional require a non-null value?
Optional.of(T) exists to allow some knowledge to be passed on. I see .of(T) as a way to make sure that the parameter is not null. If it is null, then I might have a bug somewhere, and I'll know it. While I will not know it if I use ofNullable (or at least, it'll be much harder to check). More on reddit.com
🌐 r/java
124
69
June 13, 2024
Why do we have Optional.of() and Optional.ofNullable()?
Mostly for the lambdas, but it's also an assert so you fail at the point where your expectation was violated, rather than indirectly downstream. More on reddit.com
🌐 r/java
53
55
April 7, 2025
java8 - Why use Optional in Java 8+ instead of traditional null pointer checks? - Software Engineering Stack Exchange
See a Stack Overflow Answer on ... the Java Language Architect at Oracle. ... This is what happens when you turn off your brain in the name of "best practices". Stack Exchange Broke The Law – Stack Exchange Broke The Law · 2018-01-19 04:41:49 +00:00 Commented Jan 19, 2018 at 4:41 ... That is fairly poor usage of optional but even that has benefits. With nulls everything ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
January 18, 2018
Why exactly does Brian Goetz not recommend the use of Optional everywhere a value could be null?
The idea with Optional is to force the user of the method to handle the output straight away. Being able to pass that value around is against the point of using an Optional in the first place. For example, you have a method that calls an API. If it returns empty, you should either throw an exception, or fill in some default value. If it returns a value, then unpack it. You should not have an Optional going forward. More on reddit.com
🌐 r/java
285
123
June 2, 2023
🌐
Oracle
oracle.com › java › technical details
Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional!
The first flatMap ensures that an Optional<Soundcard> is returned instead of an Optional<Optional<Soundcard>>, and the second flatMap achieves the same purpose to return an Optional<USB>. Note that the third call just needs to be a map() because getVersion() returns a String rather than an Optional object. Wow! We've come a long way from writing painful nested null checks to writing declarative code that is composable, readable, and better protected from null pointer exceptions. In this article, we have seen how you can adopt the new Java SE 8 java.util.Optional<T>. The purpose of Optional is not to replace every 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.
🌐
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.

🌐
Medium
medium.com › javarevisited › null-check-vs-optional-are-they-same-c361d15fade3
Null Check vs Optional? What's the difference ? How to use Optional | Javarevisited
November 4, 2020 - The main point of Optional is to indicate the absence of a value (i.e null value ) while returning value for the function. It was meant to clarify the intent to the caller. I believe the problem arises when Optional is used in the same way as ...
🌐
Baeldung
baeldung.com › home › java › core java › guide to java optional
Guide To Java Optional | Baeldung
February 15, 2026 - Note that we used the isPresent() method to check if there is a value inside the Optional object. A value is present only if we have created Optional with a non-null value.
🌐
GitHub
github.com › projectlombok › lombok › wiki › Language-Design:-Null-vs.-Optional
Language Design: Null vs. Optional
Let's call this concept NUI because calling it null is presumptive (solutions to the NUI problem such as Optional don't have null at all). NUI is short for 'not found, uninitialized, or irrelevant in this context'. null is also sometimes used as a property of a type system, and that is what Tony Hoare is talking about, as the above snippet of that quote shows. In java's original language design, any type in the system is to be read as 'either an X or null'.
Author   projectlombok
Find elsewhere
🌐
Baeldung
baeldung.com › home › java › core java › difference between optional.of() and optional.ofnullable() in java
Difference Between Optional.of() and Optional.ofNullable() in Java | Baeldung
May 18, 2024 - As a result, this gives rise to ... class was introduced in Java 8. Wrapping a reference in an Optional allows us to better express the possibility of a value being present or not....
🌐
University of Washington
homes.cs.washington.edu › ~mernst › advice › nothing-is-better-than-optional.html
Nothing is better than the Optional type
For some concrete examples, see http://www.codeproject.com/Articles/787668/Why-We-Should-Love-null and search for the word “cumbersome”. Optional introduces space overhead: an Optional is a separate object that consumes extra memory. Optional introduces time overhead: Its data must be accessed ...
🌐
Readthedocs
java-8-tips.readthedocs.io › en › stable › optional.html
10. Handling nulls with Optional — Java 8 tips 1.0 documentation
Optional is a container or a wrapper class that represents value might or might not exist for a variable. When value present you can use get method to fetch the value or on absent it just behaves as an empty container. We get exception when we directly operate on the null instances so Optional promotes to use its utility methods to perform operations.
🌐
Developer.com
developer.com › dzone › coding › java › how to use optionals in java
How to Use Optionals in Java
December 8, 2023 - Prior the Optional class, many developers used either null or exceptions to denote when a desired value was not present; using the Optional class, however, allows us to explicitly state when a value may or may not be present.
🌐
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 - // PREFER public String findUserStatus(long id) { Optional<String> status = ... ; // prone to return an empty Optional return status.orElseThrow(IllegalStateException::new); } When you have anOptionaland need anullreference, then use orElse(null). Otherwise, avoid orElse(null). A typical scenario for usingorElse(null)occurs when we have anOptionaland we need to call a method that acceptsnullreferences in certain cases. For example, let's look at Method.invoke()from the Java Reflection API.
🌐
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 - Java Optional and Either are two useful classes in Java that can be used to handle null values and represent one of two possible values. While Optional is used to handle null values, Either is used to represent two possible outcomes.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Optional.html
Optional (Java Platform SE 8 )
April 21, 2026 - Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.
🌐
Medium
medium.com › @navnathujadhav › understanding-the-difference-between-of-and-ofnullable-in-javas-optional-class-a8f4950d1fd9
Understanding the Difference Between of and ofNullable in Java's Optional Class | by Navnath Jadhav | Medium
May 21, 2023 - Understanding the difference between ... class in Java. of should be used when you are certain that the value is non-null, while ofNullable is suitable for scenarios where the value can be either non-null or null....
🌐
Coderanch
coderanch.com › t › 635119 › java › Optional-null
Optional vs null (Features new in Java 8 forum at Coderanch)
June 13, 2014 - Very pleased to see java.util.Optional added, along with java.util.function.Supplier and java.util.function.Consumer , to provide the possibility of a "null-free" work environment. However, given how prevalent null return values are in existing Java code, I really wonder how practical it is to attempt to use Optional everywhere in your own code to avoid null while still interacting with existing Java libraries that happily accept arguments that are value-or-null?.
Top answer
1 of 11
125

Style 2 isn't going Java 8 enough to see the full benefit. You don't want the if ... use at all. See Oracle's examples. Taking their advice, we get:

Style 3

// Changed EmployeeServive to return an optional, no more nulls!
Optional<Employee> employee = employeeServive.getEmployee();
employee.ifPresent(e -> System.out.println(e.getId()));

Or a more lengthy snippet

Optional<Employee> employee = employeeServive.getEmployee();
// Sometimes an Employee has forgotten to write an up-to-date timesheet
Optional<Timesheet> timesheet = employee.flatMap(Employee::askForCurrentTimesheet); 
// We don't want to do the heavyweight action of creating a new estimate if it will just be discarded
client.bill(timesheet.orElseGet(EstimatedTimesheet::new));
2 of 11
50

If you're using Optional as a "compatibility" layer between an older API that may still return null, it may be helpful to create the (non-empty) Optional at the latest stage that you're sure that you have something. E.g., where you wrote:

Optional<Employee> employeeOptional = Optional.ofNullable(employeeService.getEmployee());
if(employeeOptional.isPresent()){
    Employee employeeOptional= employeeOptional.get();
    System.out.println(employee.getId());
}

I'd opt toward:

Optional.of(employeeService)                 // definitely have the service
        .map(EmployeeService::getEmployee)   // getEmployee() might return null
        .map(Employee::getId)                // get ID from employee if there is one
        .ifPresent(System.out::println);     // and if there is an ID, print it

The point is that you know that there's a non-null employee service, so you can wrap that up in an Optional with Optional.of(). Then, when you call getEmployee() on that, you may or may not get an employee. That employee may (or, possibly, may not) have an ID. Then, if you ended up with an ID, you want to print it.

There's no need to explicitly check for any null, presence, etc., in this code.

🌐
Medium
medium.com › @programmingsolutions750 › lets-break-down-the-difference-between-optional-and-null-in-java-and-similar-programming-d0bc4cd4e8bc
Let’s break down the difference between Optional and null in Java (and similar programming… | by FullStack With Ram | Medium
May 17, 2025 - Throws NullPointerException if value is null. Optional.ofNullable(value) // Creates Optional that can be null or non-null. Optional.empty() // Creates an empty Optional. boolean isPresent() // Returns true if value is present. boolean isEmpty() // Returns true if value is absent. (Java 11+)
🌐
Reddit
reddit.com › r/java › why exactly does brian goetz not recommend the use of optional everywhere a value could be null?
r/java on Reddit: Why exactly does Brian Goetz not recommend the use of Optional everywhere a value could be null?
June 2, 2023 - I'm in a weird position I guess : never accept/return Optionals on the interfaces, but internally use the Optional API for nested null-handling (which AFAIK violates Goetz's advice?) Most of my collegues are old timers who are more used to C than to Java 8's lambdas, so asking them to learn about the NullObject or Optional/Maybe paradigm to work on my Java 8 projects wouldn't fly easily.