Signup/Sign In

No more NullPointerException! Start using Java 8 Optional Class

Posted in Programming   LAST UPDATED: SEPTEMBER 13, 2021

    NullPointerException is very common on Java, whenever we try to perform any operation on any variable which is not yet initialized or holds a null value, we get a NullPointerException. For long developers have been using the try-catch block to handle unexpected null pointer exceptions, but now from Java 8, a new class named Optional has been introduced to handle null values without any exception.

    The optional class can be used as a container to hold non-null objects. Developers generally use Optional class to store objects which may or may not have a null value, which can be handled using Optional class methods which informs whether a value is 'available' or 'not available' for the enclosing object or variable. In short, it's a class to encapsulate any optional value.

    Optional is introduced in the java.util package. Let's learn how we can use Optional class in our day to day coding life.

    Creating Optional Object

    As we already mentioned that Optional class is available in the java.util package, hence you will have to import that package before you use it.

    
    import java.util.Optional

    Following is the declaration of the class,

    
    public final class Optional<T> extends Object

    To initialize an Optional class object, we can use the following methods provided in the Optional class:

    1. empty()
    2. of()
    3. ofNullable()

    Let's see how we can create an empty object of the Optional class first,

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

    This will be an empty object initialization and if we use the isPresent() method to check if any value is present in the Optional object, it will return false. More on isPresent() later, now let's see how we can initialize any variable with some defined value to the Optional container,

    
    String name = "Studytonight";
    
    Optional<String> opt = Optional.of(name);

    Now the object opt will hold a string variable name. However, the argument passed to the of() method should not be null. If you think that the argument can be null for some conditions, then in such case, we use ofNullable() to initialize the Optional object, like this:

    
    String name = "Studytonight";
    
    Optional<String> opt = Optional.ofNullable(name);

    In the code above, even if variable name contains null, the code will work just fine.

    So these are the multiple ways in which we can easily use the Optional class object to hold any other object or variable that you suspect can become null during the code execution.


    Checking Value of the Optional Object

    We can use the isPresent() method to check whether the Optional object contains any value or not. It will return True if any value is enclosed inside the Optional object, otherwise, it returns False.


    Conditional Action on Optional Object

    Before Optional class, we used to use the following code for any variable that could possibly become null during program execution

    
    if(name != null)  {
    
         System.out.println(name.length());
    
    }

    Here, we are first checking whether the value is null or not, and if it is not null then only we perform any action on the variable. But this practice is repetitive, as we need to apply the same check everywhere, and chances are that we might miss it somewhere, hence making our code prone to NullPointerException.

    Using Optional object and ifPresent() method, we can follow functional programming paradigm, and accomplish the above in just a single line of code,

    
    String name = "Studytonight";
    
    Optional<String> opt = Optional.ofNullable(name);
    
    opt.ifPresent(name-> System.out.println(name.length()));

    Impressed? No yet! Let's see how we can provide a default value to a variable, to replace its value with whenever it is equal to null.


    Assigning Default Value

    orElse() method of the Optional class can be used to provide a default value to any variable or object enclosed inside the Optional object, so when the value of the enclosed object or variable is null, then the default value is used instead. For example,

    
    String name = null;
    
    Optional<String> opt = Optional.ofNullable(name).orElse("Studytonight");

    Now, in the code above, as the value of the variable name is null, hence the default value "Studytonight" will be saved in the Optional object.


    Throwing Exceptions when required

    If for any null value occurrence inside the Optional object, we can use the orElseThrow() method to throw an error and can handle the same in our code. For example,

    
    String nullVar = null;
    
    Optional<String> opt = Optional.ofNullable(nullVar).orElseThrow(
    
        IllegalArgumentException::new);

    We can use this method to throw custom exceptions too.


    Conclusion

    The Optional class comes in with a lot of methods which has made the life of all the developers easy, who are using it. So start using the Optional class wherever you can to encapsulate important variables or objects and save yourself from fixing issues of unnecessary NullPointerExceptions.

    You may also like:

    About the author:
    I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight
    Tags:Java8OptionalJava
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS