What is the difference between Optional.of() and Optional.ofNullable()?

Optional.of() and Optional.ofNullable() both construct an Optional instance, but they differ in how they treat a null argument: of() rejects null outright, while ofNullable() gracefully converts null into an empty Optional.

Key Points: • Optional.of(value) throws a NullPointerException immediately if value is null — use it only when null is truly impossible or is itself a bug. • Optional.ofNullable(value) returns Optional.empty() if value is null, and a populated Optional otherwise — use it whenever the source might legitimately be null. • Choosing of() when appropriate documents intent and fails fast, surfacing bugs earlier than letting a null silently propagate. • Both methods return the same Optional<T> type, so downstream code (orElse(), map(), etc.) is unaffected by which constructor was used. • A common mistake is using of() on a value that can be null from an external source like a database or API response, which just relocates the NullPointerException rather than eliminating it.

Example: Optional.of(new User()) is safe because the object was just created and is guaranteed non-null, whereas Optional.ofNullable(resultSet.getObject("email")) is appropriate because a database column can legitimately be null.

Code Example:

String name = "Alice";
Optional<String> safe = Optional.of(name); // fine, name is non-null

String maybeNull = getNullableValue();
Optional<String> flexible = Optional.ofNullable(maybeNull); // handles null gracefully

Interview Tip: A concise interview answer is:

"Optional.of() throws a NullPointerException right away if you pass it null, so I use it when I'm certain the value can't be null. Optional.ofNullable() instead returns an empty Optional for a null input, so I use it whenever the source — like a database field or an API response — might genuinely be null."