Java 8 Optional: Methods to create Optional object

Introduction

Optional class was added in Java 8 release under java.util package. It works as container or wrapper for actual value which may or may not have null. This helps to avoid and handle null pointer exception in cleaner way. For more details about Optional please visit Java 8 Optional page

A noteworthy point about Optional class is that it has private constructor. So we can not create optional object using new keyword. Also we can not change the value in Optional once created. Hence we need to provide the value at the time of object creation

Syntax for creating optional object

There are 3 ways to create Optional object. Using 3 different static methods provided in Optional class

  1. Using public static Optional empty() method:

    Returns the Optional instance with out null value. Optional object created using this method will be always empty

    Optional<String> emptyOptional = Optional.empty();

    Empty Optional is used to represent null value. On this object we can perform some operation without null pointer exception

  2. Using public static Optional of(T value) method:

    Whenever we need to create Optional of some value, We can use Optional.of(value) to create Optional of desired value.
    In this method null value is not allowed.
    If we try to create object with null value it throws NullPointerException.

    String name ="stacktraceguru";
    Optional<String> nameOptional = Optional.of(name );
    String name = null;
    Optional<String> nameOptional = Optional.of(name );    //Wrong

    There can be some cases when we are not sure if the value will be present or not. In such cases we should use ofNullable(value) than of(value) to avoid NullPoiterException

  3. Using public static Optional ofNullable(T value) method:

    Whenever we need to create Optional of some value and if value can be null, we should use Optional.ofNullabe(value).  This create Optional of desired value or empty if null.
    In this method null value is allowed.
    If we try to create object with null value it returns empty Optional.

    String name ="stacktraceguru";
    Optional<String> nameOptional = Optional.of(name );
    String name = null;
    Optional<String> nameOptional = Optional.of(name );    //Valid
     

Fast track reading :

    • Optional class has private constructor so we can not create object using new keyword.
    • Optional value can not be changed once created
  • Three ways to create Optional class object
Create instanceArgumentsSummary
empty()                                -Null value option is created
of(T value)Value to be set - can not be nullOptional of provided not null value
ofNullable(T value)Value to be set - can be nullOptional of value, If value is not null else empty Optional

Leave a Reply

Your email address will not be published. Required fields are marked *