0
0
JavaComparisonBeginner · 3 min read

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.

FeatureOptional.ofOptional.ofNullable
Accepts null valueNo, throws NullPointerExceptionYes, returns empty Optional
ReturnsOptional with non-null valueOptional with value or empty
Use caseWhen value is guaranteed non-nullWhen value might be null
Exception on nullThrows NullPointerExceptionNo exception, returns empty
Introduced inJava 8Java 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

java
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);
    }
}
Output
Hello
↔️

Optional.ofNullable Equivalent

java
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");
    }
}
Output
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

Use Optional.of only with guaranteed non-null values to enforce null safety.
Use Optional.ofNullable to handle values that might be null without exceptions.
Optional.of throws NullPointerException on null; Optional.ofNullable returns empty Optional.
Choosing the right method improves code clarity and null handling.
Both methods were introduced in Java 8 and are essential for modern null-safe code.