Optional class in Java

As part of java8 release Optional class introduced to deal with NullPointerExceptions that occur in Java applications. The Optional class is available in the java.util package and acts as a container that holds values which can be either non-null or empty.

    Create Optional object

    The constructor of the Optional class is private, so we cannot instantiate it directly using a constructor. Instead, we can instantiate it using static methods provided by the Optional class.

    empty()
    of()
    ofNullable()

    Creating empty optional

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

    Creating Optional using of()

    String str = "StackByt";
    Optional<String> opt1= Optional.of(str);

    The of() method will throw NullPointerException if we pass null reference to it.

    Creating Optional using ofNullable()

    String str = "StackByt";
    Optional<String> opt2 = Optional.ofNullable(str);

    The ofNullable() method returns an Optional object. If we pass a null reference, it won’t throw a NullPointerException; instead, it will simply return an empty Optional.

    Accessing the value of Optional object

    String name = "Krishna";
    Optional<String> opt= Optional.ofNullable(name);
    System.out.println(opt.get());

    The above code will work fine if the name has a value. If we pass a null , it will throw an exception (NoSuchElementException). To resolve this, we should verify first before attempting to retrieve the value. In the below example we are verifying the presence of value using isPresent()

    String name = "Krishna";
    Optional<String> opt= Optional.ofNullable(name);
    if(opt.isPresent()) {
        System.out.println(opt.get());
    }

    Returning Default values

    In the below, the name1 is null, so name2 is returned as a default instead.

     String name1 = null;
     String name2 = "Krishna";
     String result = Optional.ofNullable(name1).orElse(name2);
     System.out.println(result);  // Krishna

    If the initial value of the object is not null, then the default value is ignored.

    String name1 = "Sai";
     String name2 = "Krishna";
     String result = Optional.ofNullable(name1).orElse(name2);
     System.out.println(result);  // Sai

    Leave a Comment