Java,  Util

Avoid NullPointerExceptions with Optional

Optionals are commonly used to prevent null references and NullPointerExceptions in Java code.

An Optional is a container object which may or may not have a value. To verify if a value exists, the isPresent() method is used and to verify if an Optional is empty then the isEmpty() method can be used.

import java.util.Optional;

public class DiscoverOptional {

  public static void main(String[] args) {

   //Create an Optional object
   Optional<String> empty = Optional.empty();
   Optional<String> name = Optional.of("Naiomi");

   //Check the value of Optional
   if (name.isPresent()) {
     System.out.println(name.get());
   }

   //Check if the Optional is empty
   if (empty.isEmpty()) {
     System.out.println(empty.isEmpty());
   }
  }
}

The orElse() method is used to retrieve the value wrapped inside an Optional instance by taking a parameter that acts as a default value.

System.out.println("Hi" + name.orElse(""));

The orElseGet() takes a supplier functional interface and when invoked returns the value of the invocation.