Tuesday, July 7, 2015

Optional Class Introduction

Optional Class Introduction

In previous post we saw how to avoid null Pointer Exception using Optional<T> class. Optional class as written in Java docs is a container object. It may or may-not contain non-null value. If value is present then isPresent() method will return true and get() will return the value.

      String str = ....
      Optional<String> optional = ....

str can or cannot be null.
optional is never null. But it may or may not contain value (value is either present or empty).

Optional<T> class has private constructor so we cannot use new keyword to create object of Optional<T>.  

There are few ways to create Optional<T> object.

·         Optional<String> optional = Optional.of("Monday");
o   Returns Optional<String> with specified non-null value
o   Throws NullPointerException is value specified is null.

·         Optional<String> optional = Optional.ofNullable(null);
o   ofNullable can accept null and non-null values.
o   If value passed is null then it returns empty Optional
o   If value passed is not null then ofNullable method calls of(..) method

·         Optional<String> optional = Optional.empty();
o   empty() will return empty Optional corresponding to null.

 In next post we will dive deeper into this 3 methods.


2 comments:

  1. can i use the optional keyword as function parameter, where i just want to pass one parameter and want other to be set to optional value ?

    ReplyDelete
  2. Hi Vimal, Optional class is a container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value. This way we can avoid NullPointerException.

    To answer your question you need to pass exact number of parameters to a method. This is what we do for method overloading.

    Thanks,
    Bharat.

    ReplyDelete

Ads Inside Post