Codectionary / Developer documentation / Java

Optional

Optional<T> is a container object that may or may not hold a non-null value, designed to make the possibility of 'no result' explicit in a method's return type, reducing NullPointerExceptions. Rather than returning null and hoping callers remember to check for it, a method returning Optional<T> signals clearly that a value might be absent, and provides safe methods like isPresent(), ifPresent(), and orElse() for handling both cases.

Syntax

Optional<Type> opt = Optional.of(value);

Examples

Creating an Optional

The three main ways to construct an Optional.

import java.util.Optional;

Optional<String> present = Optional.of("Hello");
Optional<String> empty = Optional.empty();

String maybeNull = null;
Optional<String> safe = Optional.ofNullable(maybeNull);  // becomes empty, no exception

System.out.println(present.isPresent());  // true
System.out.println(empty.isPresent());     // false

Safely Retrieving Values

Using orElse() and orElseGet() to provide a fallback instead of risking a NullPointerException.

import java.util.Optional;

Optional<String> username = Optional.empty();

String result = username.orElse("Guest");
System.out.println(result);  // Guest

String result2 = username.orElseGet(() -> "Anonymous-" + System.currentTimeMillis());
System.out.println(result2);

// username.get();  // would throw NoSuchElementException - avoid calling get() directly

ifPresent() and ifPresentOrElse()

Running code conditionally based on whether a value exists, without an explicit if statement.

import java.util.Optional;

Optional<String> email = Optional.of("john@example.com");

email.ifPresent(e -> System.out.println("Sending to: " + e));

Optional<String> missingEmail = Optional.empty();
missingEmail.ifPresentOrElse(
    e -> System.out.println("Sending to: " + e),
    () -> System.out.println("No email on file")
);

Chaining map() and filter() on Optional

Optional supports its own map/filter for transforming a value only if it is present.

import java.util.Optional;

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

Optional<String> upper = name
    .map(String::toUpperCase)
    .filter(n -> n.length() > 3);

System.out.println(upper.orElse("N/A"));  // JOHN

Best practices

  • Use Optional as a return type to signal a value might be absent, but avoid using it for fields or method parameters - that is not its intended purpose
  • Prefer orElse()/orElseGet()/ifPresent() over calling .get() directly, which defeats the purpose by risking an exception just like a null check would
  • Use Optional.ofNullable() when wrapping a value that might legitimately be null, and Optional.of() only when you are certain the value is non-null
  • Chain .map() and .filter() on an Optional to transform a value safely, only if it is actually present, avoiding nested if statements

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading