Skip to content

Java 8 Optional#

Definition#

  • The Optional class in Java 8 is a container object which is used to contain a value that might or might not be present. It was introduced as a way to help reduce the number of NullPointerExceptions that occur in Java code. There are various methods available in the API to deal with the Optional in a convenient and reliable manner.

Example#

  • Create an Optional with will contain non-null value.

    1
    2
    3
    // Ex: Create an Optional Object contains non-null value
    String str = "abc";
    Optional<String> opt = Optional.of(str);
    

  • Create an Optional which may contain value or null.

    1
    2
    3
    // Ex: Create an Optional Object contains value
    // or empty if the input parameter is null
    Optional<String> opt = Optional.ofNullable(str);
    

  • Why use Optional.of over Optional.ofNullable ?

1
2
3
 String foobar = <value or null>
 Optional.of(foobar); //May throw NullPointerException
 Optional.ofNullable(foobar); //Safe from NullPointerException
  • Answer: If we expect that our foobar is never null due to the program logic, it's much better to use Optional.of(foobar) as we will see a NullPointerException which will indicate that our program has a bug. If we use Optional.ofNullable(foobar) and the foobar happens to be null due to the bug, then our program will silently continue working incorrectly, which maybe a bigger disaster. This way of error may occur much later and it would be much harder to understand at which point it went wrong.