Back to Blog
Java

Java Optional.of: Usage, Pitfalls, and When to Use It

java optional of: Understand Java Optional.of: its syntax, how it differs from ofNullable, common pitfalls, and when to use it in your code.

OptionalNull HandlingJava APIFunctional Programming
Java Optional.of method wrapping a non-null value, with a null pointer exception symbol nearby

java optional of requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.

When working with Java's Optional, the Optional.of method is often the first one developers encounter. It creates an Optional that contains a non-null value. The method is straightforward: pass a reference, and if it is null, a NullPointerException is thrown immediately. That behavior is both its strength and its trap.

What Optional.of Actually Does

Optional.of is a static factory method that returns an Optional describing a present value. The contract is simple: the argument must not be null. If you pass null, the method throws NullPointerException at the call site, not later when you try to access the value.

Optional<String> name = Optional.of("Alice");

This creates an Optional that is present and contains "Alice". The method is designed for situations where you are certain the value is non-null. It encodes that certainty in the type system, allowing downstream code to assume the value exists without an explicit null check.

The immediate exception is intentional. It fails fast, which is often preferable to propagating a null reference through several layers of code. If the value is null, the problem surfaces at the point where the Optional is created, making the root cause easier to trace.

Optional.of vs Optional.ofNullable

The most common source of confusion is choosing between Optional.of and Optional.ofNullable. The difference is how each handles null arguments.

MethodNull argument behaviorUse case
Optional.of(value)Throws NullPointerExceptionWhen you know the value is never null
Optional.ofNullable(value)Returns Optional.empty()When the value may be null

Optional.ofNullable is the safer choice when the value comes from an external source, such as a database query, a network response, or user input. It does not throw; instead, it produces an empty Optional.

String maybeNull = lookupFromDatabase(); Optional<String> result = Optional.ofNullable(maybeNull);

If maybeNull is null, result is empty. This is the typical pattern for optional values that may legitimately be absent. Optional.of is reserved for values that are guaranteed to exist by the surrounding logic.

The NullPointerException Trap

Passing null to Optional.of is a common mistake, especially when refactoring existing code that used direct null checks. Consider a method that previously returned a value that could be null, and you decide to wrap it in an Optional:

// Before public String findName() { return name; // could be null } // After public Optional<String> findName() { return Optional.of(name); // throws if name is null }

If name is null, the second version throws immediately. The refactoring changes behavior in a way that may not be intended. The fix is to use Optional.ofNullable unless the method contract guarantees a non-null return.

This trap is especially dangerous when the null value is rare. The code may work for months until a specific input triggers the null, and then the application fails at an unexpected point. The exception is thrown before any of the Optional processing logic runs, which can make debugging harder if you assumed the Optional would handle absence gracefully.

Using Optional.of in Method Returns

Optional.of is appropriate in methods that have a strict non-null contract. For example, a method that always returns a configured value, a default value, or a computed result that cannot be null.

public Optional<Configuration> getActiveConfig() { return Optional.of(config); // config is initialized in constructor }

Here, config is guaranteed to be non-null because it is assigned in the constructor and never reassigned. Using Optional.of documents that guarantee and enforces it at runtime.

Another common pattern is to use Optional.of when you have already performed a null check and want to create an Optional from a known non-null value.

if (value != null) { return Optional.of(value); } else { return Optional.empty(); }

This is essentially what Optional.ofNullable does internally, but writing it out can make the logic explicit. In practice, Optional.ofNullable is more concise and less error-prone.

Performance and Overhead

Creating an Optional has a small runtime cost. It is a wrapper object that requires allocation. For most applications, this overhead is negligible, but in high-throughput code paths, it can matter. Optional.of itself is a simple method call that returns a new instance; it does not perform any complex validation beyond the null check.

The performance concern is not specific to Optional.of; it applies to all Optional usage. If you are creating millions of Optional instances per second, the allocation pressure can affect garbage collection. In such cases, consider whether Optional is the right abstraction for the hot path. Sometimes a plain null check is more efficient and clearer.

That said, the difference between Optional.of and Optional.ofNullable is negligible. Both allocate an object; ofNullable adds a conditional branch. The real performance consideration is whether to use Optional at all, not which factory method to call.

Compatibility and Java Versions

Optional was introduced in Java 8. Optional.of and Optional.ofNullable have been available since then. No version-specific differences exist for these methods. However, the broader Optional API has evolved slightly. For example, Optional.stream() was added in Java 9, and Optional.isEmpty() in Java 11. These additions do not affect Optional.of.

When using Optional in a codebase, be aware that it is primarily designed for return types, not for fields, method parameters, or collections. Using Optional as a field type is discouraged because it adds overhead and complicates serialization. Similarly, passing Optional as a method argument is often an anti-pattern because it forces the caller to wrap values unnecessarily. Optional.of should be used in the context of returning a value from a method, not as a general-purpose null-safe container.

Edge Cases and Design Considerations

One subtle edge case is when the value passed to Optional.of is a primitive wrapper that is null. For example, an Integer that comes from a map lookup:

Map<String, Integer> scores = new HashMap<>(); Integer score = scores.get("player"); // null if key missing Optional<Integer> optionalScore = Optional.of(score); // throws

This fails because score is null. The correct approach is to use Optional.ofNullable or to check for the key's presence before calling Optional.of. The same applies to any reference type that can be null, including arrays, collections, and custom objects.

Another consideration is the interaction with Optional's orElse and orElseGet methods. If you create an Optional with Optional.of, you know it is present, so calling orElse is redundant. That redundancy can hide bugs if the value later becomes null and you switch to ofNullable without adjusting the downstream logic. Always choose the factory method that matches the actual nullability of the value.

When to Avoid Optional.of Entirely

There are cases where using Optional at all is questionable. If a method always returns a non-null value, returning Optional adds no value and forces the caller to handle the empty case unnecessarily. In that situation, a plain return type is better. Optional.of is only useful when you want to signal that a value is present but you also want to allow the caller to use Optional operations like map, filter, or orElse.

For example, a method that returns a configuration object that always exists could simply return Config instead of Optional<Config>. The caller would not need to deal with an absent case. Using Optional.of in such a method is over-engineering. Reserve Optional for values that may be absent, and use Optional.of only when you have a non-null value that you want to wrap for a specific processing chain.

A final practical note: when you see Optional.of in a code review, ask whether the value could ever be null. If the answer is "maybe," the code should use Optional.ofNullable. If the answer is "no," then Optional.of is fine, but also question whether Optional is needed at all. This simple check prevents the most common Optional misuse.

java optional of: Practical Usage and Code Examples | RYUSLOG DEV