This question is over seven years old, but I felt so frustrated by the best answer that I had to write my answer.
The reason why the existing answers, including the best one, are failing to answer the question properly is because the original question is not appropriate in the first place. If you do not set the right question, you will not get the right answer.
What is improper about the original question is that it is comparing the wrong pair. There are three static methods in java.util.Optional
.
Optional#empty()
Optional#of(T value)
Optional#ofNullable(T value)
The pair is not of
and ofNullable
, but of
and empty
. This is because these two are the factory methods that create new instances, where Optional
doesn't provide a public constructor.
You can choose from of
and empty
when you want to create a new instance of Optional
.
Optional<Integer> answer = Optional.of(42); // or Optional.empty() if it's absent
In this usage, you are sure you don't pass null
to of()
, because it is you who are initialising the instance. If you want to create an empty instance, you can just choose empty()
instead. Therefore, if you are passing a null
value to of()
at this stage, it is obviously a bug and you should receive an NPE.
One of the commenters in this question suggested that, since ofNullable
is more useful than of
, it would have been better if ofNullable
were named as of
and of
were ofNotNull
. This opinion is well taken. However, when you consider that of
and empty
are the official Optional
factory methods, it makes sense that the more commonly used one is defined with a shorter name. Furthermore, it is also a good name that is consistent with the naming of the other Java collection class factory methods such as List#of()
, Set#of()
, and Map#of()
.
So what is ofNullable
? This one is actually a utility adapter method to bridge the null-eliminated Optional
world with the legacy world full of null
s. It is used to wrap variables defined somewhere else, or return values received from external services, in Optional
to make them null-safe.
String foo = someExternalAPI();
Optional<String> bar = Optional.ofNullable(foo);
As this is a utility method rather than a primary factory method, it should be generally acceptable to give it a slightly longer name, and it is even good practice that a utility method has a descriptive name which tells its intent clearly.
Summary
- What is paired with
Optional#of(T value)
is Optional#empty()
.
- Use
of
or empty
to create a new Optional
instance.
- Use
ofNullable
to wrap an existing variable as Optional
.
java.util.Optional
- It's available if you're using JDK 8 or later – SquallyofNullable()
namedof()
and andof()
namedofNotNull()
– Auschwitz