Optional.of vs Optional.ofNullable in Java: Key Differences and Usage
Optional.of creates an Optional with a non-null value and throws NullPointerException if the value is null. Optional.ofNullable creates an Optional that can hold a null value without throwing an exception, returning an empty Optional instead.Quick Comparison
This table summarizes the key differences between Optional.of and Optional.ofNullable in Java.
| Feature | Optional.of | Optional.ofNullable |
|---|---|---|
| Accepts null value | No, throws NullPointerException | Yes, returns empty Optional |
| Returns | Optional with non-null value | Optional with value or empty |
| Use case | When value is guaranteed non-null | When value might be null |
| Exception on null | Throws NullPointerException | No exception, returns empty |
| Introduced in | Java 8 | Java 8 |
Key Differences
Optional.of requires a non-null argument and immediately throws a NullPointerException if you pass null. This makes it useful when you are sure the value exists and want to enforce that at runtime.
On the other hand, Optional.ofNullable accepts a value that can be null. If the value is null, it returns an empty Optional instead of throwing an exception. This is helpful when the value might or might not be present.
In summary, Optional.of is strict and fails fast on nulls, while Optional.ofNullable is flexible and safely handles nulls by returning an empty container.
Code Comparison
import java.util.Optional; public class OptionalOfExample { public static void main(String[] args) { String value = "Hello"; Optional<String> optional = Optional.of(value); System.out.println(optional.get()); // Uncommenting the below line will throw NullPointerException // Optional<String> optionalNull = Optional.of(null); } }
Optional.ofNullable Equivalent
import java.util.Optional; public class OptionalOfNullableExample { public static void main(String[] args) { String value = null; Optional<String> optional = Optional.ofNullable(value); System.out.println(optional.isPresent() ? optional.get() : "Empty Optional"); } }
When to Use Which
Choose Optional.of when you are certain the value is never null and want to catch errors early by throwing an exception if null appears.
Choose Optional.ofNullable when the value might be null and you want to safely handle that case without exceptions, using an empty Optional to represent absence.
Key Takeaways
Optional.of only with guaranteed non-null values to enforce null safety.Optional.ofNullable to handle values that might be null without exceptions.Optional.of throws NullPointerException on null; Optional.ofNullable returns empty Optional.