Optional<T> wraps a value that may or may not be present, and its main real value is documentation: a method returning Optional<User> tells callers directly, in the type signature, that there might be no result — unlike returning a plain User reference that could silently be null with no warning. Optional is not, however, a comprehensive null-safety mechanism the way Kotlin's or TypeScript's null handling is: ordinary Java references can still be null anywhere else in the language, and Optional itself is a regular object reference that can technically be assigned null (a misuse the official guidance explicitly warns against).
Creating and unwrapping an Optional
Calling get() without checking isPresent() first defeats the entire purpose of using Optional — it throws NoSuchElementException on an empty Optional, just trading one runtime exception for another.
Optional<String> present = Optional.of("hello");
Optional<String> empty = Optional.empty();
if (present.isPresent()) {
System.out.println(present.get()); // "hello"
}
// idiomatic: avoid isPresent()+get(), prefer these instead:
String value = empty.orElse("default"); // "default"
present.ifPresent(v -> System.out.println(v)); // runs only if presentOptional in a method signature: the real use case
findById returning Optional<User> forces every caller to explicitly handle the not-found case — the compiler won't let you accidentally treat the result as a guaranteed User the way a plain method returning User (possibly null) would.
public Optional<User> findById(int id) {
User user = database.lookup(id); // might be null
return Optional.ofNullable(user); // wraps null as Optional.empty()
}
User user = repository.findById(42)
.orElseThrow(() -> new NoSuchElementException("User not found"));What Optional is NOT for
The official Optional Javadoc's API Note says it's "primarily intended for use as a method return type" — it doesn't spell out fields, parameters or collections by name. That more specific advice against those three uses comes from the JDK architects themselves, in talks and write-ups by Brian Goetz (Java's language architect) rather than the class's own documentation. Either way, the guidance is consistent: overusing Optional outside return values adds boxing overhead and complexity without the corresponding benefit, and NullPointerException remains a real, common exception throughout ordinary Java code that never touches Optional at all.