thecodex.expert · The Codex Family of Knowledge
Java

Optional and Null Safety

Optional makes a method’s "this might have nothing to return" explicit in its signature — but Java still has plain null everywhere else, and Optional itself can be null if misused.

Java 21 LTS Since Java 8 Last verified:
Canonical Definition

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.

JavaOptionalBasics.java
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 present

Optional 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.

JavaUserRepository.java
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 Java documentation explicitly recommends against using Optional as a field type, a method parameter type, or inside a collection — it's specifically designed as a return type. Overusing it elsewhere 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.

Sources

1
Oracle. Java SE 25 API, "Optional<T>," docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Optional.html.