Java Optional Creation

Java `Optional` represents a value that may be present or absent, and its factory methods make that state explicit. The main creation choices are `Optional.of`, `Optional.ofNullable`, and `Optional.empty`.

Use `Optional.of(value)` when the value is known to be non-null. Passing `null` to this method throws `NullPointerException`, so it is appropriate when null would indicate a programming error or when a non-null invariant is already guaranteed.

Use `Optional.ofNullable(value)` when the input may legitimately be null. A non-null input produces an `Optional` containing that value, while `null` produces an empty `Optional`.

Use `Optional.empty()` when you intentionally need an `Optional` containing no value. It is useful for returning an absent result from a method whose return type is `Optional<T>`.

These factory methods do not retrieve or transform values; they create the `Optional` container. In backend code, the creation method should match the nullability contract of the value being wrapped.

Key points

Interview questions

What happens if you call `Optional.of(null)`?

The call throws `NullPointerException`. `Optional.of` is specifically intended for a value that is already known to be non-null. If null is an expected input, `Optional.ofNullable` should be considered instead.

What is the difference between `Optional.of` and `Optional.ofNullable`?

`Optional.of` is used when the supplied value must be non-null. If the argument is null, it throws `NullPointerException`. `Optional.ofNullable` is intended for values that may be null and creates an empty `Optional` in that case.

When would you use `Optional.empty()`?

Use `Optional.empty()` when a method needs to return an `Optional` that contains no value. It makes the absence explicit without returning a null reference. This is commonly useful when an operation has no matching result.

How should you choose an Optional creation method in backend code?

Start with the nullability contract of the source value. If the value is guaranteed to be non-null, `Optional.of` expresses that assumption and exposes a violation through an exception. If null is a valid representation of no result, `Optional.ofNullable` preserves that distinction by producing an empty `Optional`. If the method has no value to return independently of an input, `Optional.empty()` directly expresses the absent result.