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
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Optional.html
Optional (Java Platform SE 8 )
April 21, 2026 - If a value is present the result must include its string representation in the result. Empty and present Optionals must be unambiguously differentiable. ... Java™ Platform Standard Ed.
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.

Discussions

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
Java and Optional - Language Design - Kotlin Discussions
Are there any plans to add nullable sugar to java.util.Optional? I’m not saying that generated APIs should use them where previously there were nullable return types, but being able to treat Optional values as nullable from other APIs or, when implementing interfaces from those APIs, return ... More on discuss.kotlinlang.org
🌐 discuss.kotlinlang.org
1
August 12, 2018
Optional.ofNullable + Optional value should only be accessed after calling isPresent()
Due to some reason, our optional value can be null. So that is why we are using the below statement. if(Optional.ofNullable(aliMnsId).isPresent()){ aliMnsId.get() } In that case Sonarqube should not throw this error “Optional value should only be accessed after calling isPresent()” More on community.sonarsource.com
🌐 community.sonarsource.com
2
0
December 8, 2021
Optional.ofNullable should not be used on a primitive type
Optional.ofNullable should only be used with non-null arguments. As primitive types can not hold a null-value, it makes sense to use Optional.of instead. The rule should validate that the argument is not a primitive type or a method returning a primitive type. More on community.sonarsource.com
🌐 community.sonarsource.com
1
0
February 2, 2021
🌐
GeeksforGeeks
geeksforgeeks.org › java › optional-ofnullable-method-in-java-with-examples
Optional ofNullable() method in Java with examples - GeeksforGeeks
July 12, 2025 - If the specified value is null, then this method returns an empty instance of the Optional class. Below programs illustrate ofNullable() method: Program 1: ... // Java program to demonstrate // Optional.ofNullable() method import java.util.*; ...
🌐
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 wrapped value is not null. Also, as of Java 11, we can do the opposite with the isEmpty method: @Test public void givenAnEmptyOptional_thenIsEmptyBehavesAsExpected() { Optional<String> opt = Optional.of("Baeldung"); assertFalse(opt.isEmpty()); opt = Optional.ofNullable(null); assertTrue(opt.isEmpty()); } The ifPresent() method enables us to run some code on the wrapped value if it’s found to be non-null.
🌐
Medium
medium.com › @AlexanderObregon › javas-optional-ofnullable-method-explained-1263612e5b22
Java’s Optional.ofNullable() Method Explained | Medium
August 7, 2024 - It is part of the java.util package ... various methods, Optional.ofNullable() stands out as a convenient way to create an Optional object from a value that might be null....
Find elsewhere
🌐
Javacodehouse
javacodehouse.com › blog › java-optional-use
Java Optional | How and When to use it
January 4, 2024 - In Java 8, the Optional class was ... Use Optional.of(value) when you are certain that the value is non-null. Use Optional.ofNullable(value) when the value might be null....
🌐
Java Pro Academy
javapro.academy › java-optional-of-vs-ofnullable-vs-empty
Java Optional Of Vs Ofnullable Vs Empty — Java Pro Academy
February 2, 2026 - Learn about java optional of vs ofnullable vs empty with hands-on Java code examples.
🌐
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"); ... Can be used to locate inspection in e.g. Qodana configuration files, where you can quickly enable or disable it, or adjust its settings. ... Path to the inspection settings via IntelliJ Platform IDE Settings dialog, when you need to adjust inspection settings directly from your IDE. Settings or Preferences | Editor | Inspections | Java | Probable bugs
🌐
Wordpress
khalidoubelque.wordpress.com › java8 › optional-ofnullable-and-orelsethrow-and-flatmap-in-java
Optional ofNullable() and orElseThrow() and flatmap in Java 8
November 17, 2024 - The ofNullable() method of java.util.Optional class in Java is used to get an instance of this Optional class with the specified value of the specified type. If the specified value is null, then this method returns Optional.empty.
🌐
Kotlin Discussions
discuss.kotlinlang.org › language design
Java and Optional - Language Design - Kotlin Discussions
August 12, 2018 - Are there any plans to add nullable sugar to java.util.Optional? I’m not saying that generated APIs should use them where previously there were nullable return types, but being able to treat Optional values as nullable from other APIs or, when implementing interfaces from those APIs, return ...
🌐
Hackajob
hackajob.com › talent › blog › using-the-optional-feature-in-java-8
Using the Optional Feature in Java 8
October 9, 2023 - The ‘Optional.ofNullable’ method can be used to create an 'Optional' that can hold both a null AND non-null value.
🌐
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.
🌐
Tom Gregory
tomgregory.com › java-optional
Optional in Java: Everything You Need To Know | Tom Gregory
July 17, 2022 - As an alternative to using Optional for a class variable, consider just setting the value to null. When you retrieve the value, you can pass it to Optional.ofNullable, which will either create an Optional with a value or an empty Optional.
🌐
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 a value is present, returns an Optional describing (as if by ofNullable(T)) the result of applying the given mapping function to the value, otherwise returns an empty Optional.
🌐
Sonar Community
community.sonarsource.com › rules and languages › new rules / language support
Optional.ofNullable should not be used on a primitive type - New rules / language support - Sonar Community
February 2, 2021 - Optional.ofNullable should only be used with non-null arguments. As primitive types can not hold a null-value, it makes sense to use Optional.of instead. The rule should validate that the argument is not a primitive type or a method returning ...
🌐
Educative
educative.io › answers › what-is-the-optional-ofnullable-method-in-java
What is the Optional. ofNullable() method in Java?
This method returns an Optional object with the specified value. If the argument value is null, then an empty Optional object is returned. The below code shows how to use the ofNullable() method: