Java Optional Explained: of() vs ofNullable() vs empty() with Examples
Optional is used to avoid null-related issues and represent a value that may or may not be present. You have three common ways to create an Optional. Each…
Optional is used to avoid null-related issues and represent a value that may or may not be present.
You have three common ways to create an Optional. Each behaves differently.
1. Optional.of()
Optional<String> opt1 = Optional.of("Java");
Meaning
This creates an Optional that must contain a non-null value.
Key Point
If you pass null, it will throw a NullPointerException.
Example
Optional<String> opt = Optional.of(null); // Runtime Exception
When to use
Use this when you are completely sure the value is not null.
2. Optional.ofNullable()
Optional<String> opt2 = Optional.ofNullable(null);
Meaning
This creates an Optional that can handle null safely.
Behavior
If value is not null, Optional contains the value.
If value is null, Optional becomes empty.
Example
Optional<String> optA = Optional.ofNullable("Java"); // contains value
Optional<String> optB = Optional.ofNullable(null); // empty Optional
When to use
Use this when the value may or may not be null. This is the most commonly used method in real-world applications.
3. Optional.empty()
Optional<String> opt3 = Optional.empty();
Meaning
This creates an empty Optional with no value.
Equivalent to
Optional<String> opt = Optional.ofNullable(null);
When to use
Use this when you explicitly want to represent no value.
Quick Comparison
| Method | Accepts null | Behavior |
|---|---|---|
| of() | No | Throws exception if null |
| ofNullable() | Yes | Converts null to empty Optional |
| empty() | Yes | Always returns empty Optional |
Interview Insight
A very common interview question is the difference between of() and ofNullable().
Best answer
of() is used when the value is guaranteed to be non-null and throws an exception otherwise, while ofNullable() safely handles null values by returning an empty Optional.
Key Takeaways
Use of() when null is not possible.
Use ofNullable() when null is possible.
Use empty() when you want to explicitly represent no value.