Sobes.tech
Senior

What is the purpose of the Optional class?

sobes.tech AI

Answer from AI

The Optional class in Java is used to explicitly represent a value that may be present or absent (null). It helps to avoid NullPointerException errors and makes the code more readable and safe.

Optional allows:

  • Explicitly indicate that a value may be missing.
  • Use convenient methods to handle missing values (e.g., orElse, ifPresent).
  • Avoid direct null checks.

Example of usage:

Optional<String> name = Optional.ofNullable(getUserName());

name.ifPresent(n -> System.out.println("User name: " + n));

String defaultName = name.orElse("Guest");

Here, getUserName() may return null, but Optional helps to work safely with this value.

What is the purpose of the Optional class? — Java - sobes.tech