How to avoid NullPointerException in Java using Optional class?

In order to learn how to avoid an error, we must first understand the error.

NullPointerException

NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when program attempts to use an object reference that has the null value.

These can be:



  • Invoking a method from a null object.
  • Accessing or modifying a null object’s field.
  • Taking the length of null, as if it were an array.
  • Accessing or modifying the slots of null object, as if it were an array.
  • Throwing null, as if it were a Throwable value.
  • When you try to synchronize over a null object.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to show NullPointerException
  
public class Example {
    public static void main(String[] args)
    {
  
        // Create a String of size 10
        String[] a = new String[10];
  
        // The String is empty
        // So a[1] will have null at present
        String upcase = a[1].toUpperCase();
  
        System.out.print(upcase);
    }
}

chevron_right


Output:

Exception in thread "main" java.lang.NullPointerException
    at Example.main(Example.java:4)

How to avoid NullPointerException with Optional Class?:
Java 8 has introduced a new class Optional in java.util package. It can help in writing a neat code without using too many null checks. By using Optional, we can specify alternate values to return or alternate code to run. This makes the code more readable because the facts which were hidden are now visible to the developer.

Optional Class
Optional is a container object that can contain a non-null or null value. It basically checks whether the memory address has an object or not. If a value is present, isPresent() will return true and get() will return the value. Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() which returns a default value if value, not present and ifPresent() which executes a block of code if the value is present. This is a value-based class, i.e their instances are: