liveBook · Manning

Option

As explained in 100 Java Mistakes and How to Avoid Them

Optional is a Java standard-library container type representing either a present non-null value or an empty state.

Optional is a Java standard-library container that represents either a present non-null value or an empty state. Use it when absence is a legitimate outcome, especially for methods such as searches that may find nothing. An empty Optional makes that possibility explicit to callers instead of exposing an unexpected null. section 5.1 section 5.1.2

Choose the construction method according to what null means:

  • Optional.empty() creates an absent value. section 5.1.2
  • Optional.of(value) creates a present value and throws NullPointerException if value is null; use it when non-nullness is expected so an exception exposes an upstream bug. section 5.1.2
  • Optional.ofNullable(value) converts null to empty, but should not be used indiscriminately because it can conceal a value that was incorrectly null. section 5.1.2
  • Prefer Optional as a return type, do not return null from an Optional-returning method, and generally avoid Optional parameters because callers must wrap inputs. section 5.1.2
public Optional<User> findUser(String name) {
  if (!userExists(name)) {
    return Optional.empty();
  }
  return Optional.of(getExistingUser(name));
}

A search method returns Optional.empty() when no user exists and Optional.of() for an existing user. section 5.1.2

String fullName = findUser(name).map(User::fullName)
                                .orElse("(no such user)");

A fluent map-and-orElse chain extracts a user's full name or supplies a fallback when the result is empty. section 5.1.2

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Defines empty and non-empty states, factory methods, fluent transformation, and parameter guidance, but does not detail implementation internals.
Examples
Uses a user-search result, Optional.empty(), Optional.of(), Optional.ofNullable(), map(), and orElse().
What it assumes
Assumes familiarity with Java null values and method contracts; teaches explicit absent-value signaling and construction choices.
What you can do after
Apply Optional through its factory and transformation methods when absence belongs in a return value.
How it connects
Connects Optional with null, nullability, NullPointerException, annotations, and static analysis.

Also explained in

Compare how 9 books explain option →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.