Optional.of(): Wrapping Non-Null Values
What you'll learn: How to safely wrap values you know are not null using Optional.of(), and why it immediately fails if you're wrong.
The Purpose of Optional.of()
When you have a value that you're confident is not null, Optional.of() creates an Optional container that wraps that value. Think of it as putting a guaranteed-present object into a transparent box with a label that says "contents verified."
The key characteristic: Optional.of() is strict. If you accidentally pass null to it, it throws a NullPointerException immediately, right at the point of wrapping. This is intentional design—it fails fast rather than hiding the problem.
When to Use Optional.of()
Use Optional.of() when:
- You're returning a value that should never be null
- You want to enforce that a value exists at wrapping time
- You're converting non-null values into Optional for API consistency
String username = "Alice";
Optional<String> optionalName = Optional.of(username); // Works fine
String nullValue = null;
Optional<String> broken = Optional.of(nullValue); // Throws NullPointerException immediately!
The Safety Guarantee
By throwing immediately on null, Optional.of() acts as a guard. It prevents you from creating an Optional that appears to contain something but actually wraps null—a situation that would defeat Optional's entire purpose.
public Optional<User> findAdminUser() {
User admin = getAdminFromDatabase(); // Guaranteed non-null by contract
return Optional.of(admin); // Safe wrapping
}
Key Takeaway: Use Optional.of() to wrap values you're certain are non-null; it enforces this guarantee by throwing NullPointerException immediately if passed null, creating a fail-fast safety mechanism.