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








