Course contentsShow
← Java
Lesson 1766 of 2,87037. Optional for Null SafetyFree lesson

When to Use of() vs ofNullable()

Learn the decision criteria: use of() when you guarantee non-null, ofNullable() when null is possible.

When to Use of() vs ofNullable()

You'll learn the simple decision rule for choosing between Optional.of() and Optional.ofNullable() based on whether null is possible.

The Core Decision Criteria

Both methods create an Optional, but they handle null differently:

  • Use Optional.of(value) when you guarantee the value is never null. If it turns out to be null, you want the code to fail immediately with a NullPointerException. This acts as a safety check—if null appears, it's a bug in your code.

  • Use Optional.ofNullable(value) when the value might be null, and you want to handle that possibility gracefully. It safely wraps the value, creating an empty Optional if the value is null.

Think of It Like This

Imagine of() as a strict contract: "I promise this box contains something real." If you hand it an empty box (null), it complains loudly because you broke your promise.

ofNullable() is more forgiving: "This box might be empty, and that's okay." It checks for you and handles both cases smoothly.

When to Choose Which

Choose of() when:

  • You've already validated the value isn't null
  • A null value represents a programming error
  • You're working with the result of a method that guarantees non-null

Choose ofNullable() when:

  • The value comes from external sources (user input, databases, APIs)
  • null is a legitimate, expected state
  • You're converting legacy nullable code to Optional

Key Takeaway: Use of() for guaranteed non-null values where null is a bug; use ofNullable() when null is a valid possibility you need to handle gracefully. The choice documents your intent and helps catch errors early.