Sobes.tech
Junior — Middle

Can you explain what the Optional class in the Java programming language is?

sobes.tech AI

Answer from AI

In Java, the Optional<T> class represents a container that may either contain a value of type T or be empty (absence of a value). It helps to avoid errors related to null (for example, NullPointerException) and makes the code more readable and safe.

Main features of Optional:

  • Creating an object with or without a value:

    Optional<String> maybeName = Optional.of("Alice");
    Optional<String> empty = Optional.empty();
    
  • Checking for the presence of a value:

    if (maybeName.isPresent()) {
        System.out.println(maybeName.get());
    }
    
  • Alternative actions when the value is absent:

    String name = maybeName.orElse("Unknown");
    

Using Optional helps to explicitly handle the possible absence of a value, reducing the risk of errors.