to sum it up, In the end, if you add orElseThrow(nullPoint) Are of or ofNullable the same result?

No. To see this, simply look at the types.

Copypublic static <T> Optional<T> of(T value);

public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)
                               throws X extends Throwable;

Optional.of returns an Optional<T>, where orElseThrow is going to leave you with a T. So Optional.ofNullable(x).orElseThrow(...) is really just a very roundabout

Copyif (x == null) {
  throw new NullPointerException(...);
}

You're not actually doing anything with the Optional, just making one and discarding it in a really verbose way. So if that's your intent, just do an explicit null check; there's no need at all for Optional.

Which raises the question of why we would use of or ofNullable. With the introduction of Optional, there are now two ways to represent the concept of "this value might not exist" in Java: null and Optional.empty(). People on the Internet will argue till the end of time about which is better and when you should use which one (I have strong opinions on this which I'll refrain from sharing here, since it's not what you asked), but the point is that there are two different ways to do it.

For the rest of this post, I'll borrow a bit of notation from Kotlin and write T? to mean "a T value which might be null". It's not valid Java notation, but it gets the point across. So if we want to represent "A T which may or may not exist" in Java, we can use either Optional<T> or T?.

If we want to go from T? to Optional<T>, that's what Optional.ofNullable is for. It says "If the thing is null, give me Optional.empty(); otherwise give me the thing in an Optional". To go the other way, we can use Optional.orElse(null), which says "If I have a T, give it to me, otherwise show me null". So now we have a way to convert between the two approaches. So what's Optional.of for?

You should view Optional.of as an assertion of sorts. If Java had nullable types like Kotlin, then the difference would be something like

Copypublic static <T> Optional<T> of(T value);
public static <T> Optional<T> ofNullable(T? value);

That is, ofNullable expects that its value might be null. of is already assuming that it's not. Optional.of should be thought of an assertion that the value you're giving it is not null. If that assertion fails, we throw NullPointerException immediately rather than letting errors propagate to other parts of the program. If you're calling Optional.of and recovering from the NullPointerException it throws[1], then you are doing something very wrong. That function is an assertion we were dealing with non-null data to begin with, and if that assertion fails then your program should fail immediately with a good stack trace.

It sounds like, based on your use case, you have a value that might be null. In that case, Optional.ofNullable makes sense; it's prepared to handle the use case. If you want to throw a custom exception, you should do a null check beforehand (since you're the one handling the null, not Optional) and then call Optional.of. Or, of course, you can just do an old-fashioned null check and not use Optional at all, if you're planning to extract it anyway with orElseThrow. Certainly, the pipeline Optional.ofNullable(value).orElseThrow(...) in one line would be a code smell.


[1] Note that I say "recovering from", not "catching". A nice top-level catch (Exception exc) which logs all errors is perfectly acceptable and generally a good idea in larger applications. But if you're doing catch (NullPointerException exc) { return 0; } or something like that then you need to reconsider which Optional method you should be using.

Answer from Silvio Mayolo on Stack Overflow
🌐
Medium
medium.com › @AlexanderObregon › javas-optional-ofnullable-method-explained-1263612e5b22
Java’s Optional.ofNullable() Method Explained | Medium
August 7, 2024 - To create an Optional object using ofNullable(), simply pass the value that may be null to the method: Optional<String> optionalString = Optional.ofNullable(getNullableString()); In this example, optionalString will be an empty Optional if ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › optional-ofnullable-method-in-java-with-examples
Optional ofNullable() method in Java with examples - GeeksforGeeks
July 12, 2025 - Below programs illustrate ofNullable() ... Optional.ofNullable() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op1 = Optional.ofNullable(9455); // print value ...
Discussions

java - What is the difference between Optional.ofNullable() and `Optional.of() - Stack Overflow
For the rest of this post, I'll ... if we want to represent "A T which may or may not exist" in Java, we can use either Optional or T?. If we want to go from T? to Optional, that's what Optional.ofNullable is for.... More on stackoverflow.com
🌐 stackoverflow.com
java - Why use Optional.of over Optional.ofNullable? - Stack Overflow
One of the commenters in this question ... 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 ... More on stackoverflow.com
🌐 stackoverflow.com
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
When somethings is null: Optional.ofNullable.orElse/ifPresent vs if-else
Optional should only be used as a method return type. You should never wrap a local variable in Optional.ofNullable() just to check if it is null. That makes no sense. The object creation isn't free performance wise and it simply adds nothing. Just do a simple null check with an if statement. More on reddit.com
🌐 r/java
72
33
June 14, 2021
🌐
Baeldung
baeldung.com › home › java › core java › guide to java optional
Guide To Java Optional | Baeldung
February 15, 2026 - @Test public void givenOptional_whenIsPresentWorks_thenCorrect() { Optional<String> opt = Optional.of("Baeldung"); assertTrue(opt.isPresent()); opt = Optional.ofNullable(null); assertFalse(opt.isPresent()); } This method returns true if the ...
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Optional ofNullable() method (With Examples) - Java Code Geeks
July 12, 2020 - In this tutorial, We’ll learn Optional ofNullable() example on how to create new Java 8 Optional object for any value or null value.
🌐
JetBrains
jetbrains.com › help › inspectopedia › OptionalOfNullableMisuse.html
Use of Optional.ofNullable with null or non-null argument | Inspectopedia Documentation
March 31, 2026 - Optional<String> empty = Optional.ofNullable(null); // should be Optional.empty(); Optional<String> present = Optional.ofNullable("value"); // should be Optional.of("value"); By ID · Can be used to locate inspection in e.g. Qodana configuration ...
🌐
Medium
medium.com › @mtl98 › dealing-with-optional-of-and-optional-ofnullable-in-java-3843cef75e32
Dealing with Optional.of() and Optional.ofNullable() in Java | by Mohammed Taoufik Lahmidi | Medium
February 14, 2024 - Avoiding NullPointerExceptions: By returning an empty Optional when given a null value, Optional.ofNullable() helps prevent NullPointerExceptions, offering a safer alternative to traditional null-checking approaches.
Find elsewhere
Top answer
1 of 2
15

to sum it up, In the end, if you add orElseThrow(nullPoint) Are of or ofNullable the same result?

No. To see this, simply look at the types.

Copypublic static <T> Optional<T> of(T value);

public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)
                               throws X extends Throwable;

Optional.of returns an Optional<T>, where orElseThrow is going to leave you with a T. So Optional.ofNullable(x).orElseThrow(...) is really just a very roundabout

Copyif (x == null) {
  throw new NullPointerException(...);
}

You're not actually doing anything with the Optional, just making one and discarding it in a really verbose way. So if that's your intent, just do an explicit null check; there's no need at all for Optional.

Which raises the question of why we would use of or ofNullable. With the introduction of Optional, there are now two ways to represent the concept of "this value might not exist" in Java: null and Optional.empty(). People on the Internet will argue till the end of time about which is better and when you should use which one (I have strong opinions on this which I'll refrain from sharing here, since it's not what you asked), but the point is that there are two different ways to do it.

For the rest of this post, I'll borrow a bit of notation from Kotlin and write T? to mean "a T value which might be null". It's not valid Java notation, but it gets the point across. So if we want to represent "A T which may or may not exist" in Java, we can use either Optional<T> or T?.

If we want to go from T? to Optional<T>, that's what Optional.ofNullable is for. It says "If the thing is null, give me Optional.empty(); otherwise give me the thing in an Optional". To go the other way, we can use Optional.orElse(null), which says "If I have a T, give it to me, otherwise show me null". So now we have a way to convert between the two approaches. So what's Optional.of for?

You should view Optional.of as an assertion of sorts. If Java had nullable types like Kotlin, then the difference would be something like

Copypublic static <T> Optional<T> of(T value);
public static <T> Optional<T> ofNullable(T? value);

That is, ofNullable expects that its value might be null. of is already assuming that it's not. Optional.of should be thought of an assertion that the value you're giving it is not null. If that assertion fails, we throw NullPointerException immediately rather than letting errors propagate to other parts of the program. If you're calling Optional.of and recovering from the NullPointerException it throws[1], then you are doing something very wrong. That function is an assertion we were dealing with non-null data to begin with, and if that assertion fails then your program should fail immediately with a good stack trace.

It sounds like, based on your use case, you have a value that might be null. In that case, Optional.ofNullable makes sense; it's prepared to handle the use case. If you want to throw a custom exception, you should do a null check beforehand (since you're the one handling the null, not Optional) and then call Optional.of. Or, of course, you can just do an old-fashioned null check and not use Optional at all, if you're planning to extract it anyway with orElseThrow. Certainly, the pipeline Optional.ofNullable(value).orElseThrow(...) in one line would be a code smell.


[1] Note that I say "recovering from", not "catching". A nice top-level catch (Exception exc) which logs all errors is perfectly acceptable and generally a good idea in larger applications. But if you're doing catch (NullPointerException exc) { return 0; } or something like that then you need to reconsider which Optional method you should be using.

2 of 2
3

First of all, I know the difference between the two methods.

Optional.of : Used to ensure that there is no null, if null is entered, nullPointExcepction

Optional.ofNullable : may or may not be null. Used to respond flexibly.

There's a clear point of misunderstanding.

The purpose of Optional.of() is not "to ensure that there is no null". It is not meant to be used as an assertion that a value that was passed into it is non-null. For such a validation you can use Objects.requireNonNull(), it'll either throw an NPE, or will return you a non-null value.

In order to be on the same page, the first important thing you have to keep in mind is that optionals were introduced in the JDK for only one particular purpose - to serve as a return type. Any other cases when optional is utilized as a parameter-type, or a field-type, or when optional objects are being stored in a collection isn't considered to be a good practice. As well, as creating an optional just in order to chain methods on it or to hide a null-check is considered to be an antipattern.

Here is a couple of quotes from the answer by @StuartMarks, developer of the JDK:

The primary use of Optional is as follows:

Optional is intended to provide a limited mechanism for library method return types where there is a clear need to represent "no result," and where using null for that is overwhelmingly likely to cause errors.

A typical code smell is, instead of the code using method chaining to handle an Optional returned from some method, it creates an Optional from something that's nullable, in order to chain methods and avoid conditionals.

I also suggest you to have a look at this answer to the question "Should Optional.ofNullable() be used for null check?", also by Stuart Marks.

With all that being said, combination Optional.of().orElseThrow() is both wrong and pointless:

  • If provided data is null method of() will raise an NPE and orElseThrow() will not be executed (i.e. its exception will get never be fired).
  • You're abusing the optional by creating an optional object not in order to return a nullable variable wrapped by it, but to hide the null-check (take a look at the quote above). That obscures the purpose of your code. You can use Objects.requireNonNull() instead to throw an exception if the given value must not be null or requireNonNullElse() to provide a default value.

For the same reason, you shouldn't use Optional.ofNullable().orElseThrow() at the first place.

Optional is like a Box

You might think of optional is if it is a parcel. When you need to send something, you go to the post office (i.e. returning from the method), where the thing that has to be sent is being placed into a box. When somebody (i.e. the caller) receives the parcel, it is being immediately unpacked. That is the whole lifecycle of the box called Optional.

When, according to the logic of your application, an object required to be returned from the method should not be null - use Optional.of(). It'll either send a parcel successfully or will emphasize that there's a problem by raising a NullPointerException.

If the given object is nullable by its nature, i.e. null isn't an abnormal case, then use Optional.ofNullable(), it'll fire either a box containing the object or an empty box.

And the caller (i.e. method that invokes the method returning an optional) is the one who has to unpack the box using a variety of tools that optional provides like orElseThrow(), orElseGet(), ifPresent(), etc.

🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
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 - If the provided value is non-null, it will be wrapped in an Optional; otherwise, it returns an empty Optional (Optional.empty()). ... In this example, optionalAddress is created using Optional.ofNullable with the possibly null value address.
🌐
iO Flood
ioflood.com › blog › java-optional
Java Optional: Managing Nullable Object References
February 20, 2024 - To create an Optional object, you can use one of three methods: Optional.of(), Optional.ofNullable(), and Optional.empty(). Optional<String> optionalOf = Optional.of('Hello'); Optional<String> optionalOfNullable = Optional.ofNullable(null); ...
🌐
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.
🌐
Javaprogramto
javaprogramto.com › 2020 › 05 › java-8-optional-ofnullable.html
Optional ofNullable() method (With Examples)
May 25, 2020 - This method also is a static method as empty() and of() methods of Optional class. This will not throw any runtime exception for any value. An example scenario where to use ofNullable() method. And also seen its internal implementation logic. Full example code on GitHub API ref ... Please do not add any spam links in the comments section. ... Java Reading Environment Variable - System.getEnv(...
🌐
JavaBeat
javabeat.net › home › how to use optional.ofnullable() method in java
How to Use Optional.ofNullable() Method in Java
August 31, 2023 - Optional<Integer> option2= Optional.ofNullable(null); System.out.println("Optional 2: "+ option2); } } For this specific method, we need to import the library of Java which is java.util.
🌐
Java Guides
javaguides.net › 2022 › 11 › optional-empty-of-ofnullable-methods.html
Optional empty, of, ofNullable() Methods
November 20, 2022 - Optional<String> stringOptional = Optional.ofNullable("ramesh@gmail.com"); ... import java.util.Optional; public class OptionalDemo { public static void main(String[] args) { String email = "ramesh@gmail.com"; // of, empty, ofNullable ...
🌐
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 - For example, if you have a method ... value safely. String value = null; Optional<String> optionalValue = Optional.ofNullable(value); if (optionalValue.isPresent()) { System.out.println(optionalValue.get()); }...
🌐
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 - We should use the Optional.ofNullable() static factory method when we have a reference that may or may not be null. Thus, we won’t encounter a NullPointerException for a reference that’s null.
Top answer
1 of 6
462

Your question is based on assumption that the code which may throw NullPointerException is worse than the code which may not. This assumption is wrong. If you expect that your foobar is never null due to the program logic, it's much better to use Optional.of(foobar) as you will see a NullPointerException which will indicate that your program has a bug. If you use Optional.ofNullable(foobar) and the foobar happens to be null due to the bug, then your program will silently continue working incorrectly, which may be a bigger disaster. This way an error may occur much later and it would be much harder to understand at which point it went wrong.

2 of 6
34

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 nulls. 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.
🌐
Hackajob
hackajob.com › talent › blog › using-the-optional-feature-in-java-8
Using the Optional Feature in Java 8
October 9, 2023 - Optional<String> opStr = Optional.ofNullable(“Hello World”); The above example creates a ‘String Optional’ that corresponds to the String “Hello World”.
🌐
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 - Java public static Optional<Wallet> getWallet(){ return Optional.ofNullable(null); } Using the Optional.of() method we can create non-nullable optional objects. Java public static Optional<Wallet> getWallet(){ return Optional.of(new Wallet(100)); ...