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:

  • Final and immutable (though may contain references to mutable objects).
  • Considered equal solely based on equals(), not based on reference equality(==).
  • Do not have accessible constructors.
  • Syntax:

    Optional is a generic type of type T.
    
    Optional<T>
    

    Rectifying the code for the above NullPointerException using Optional Class:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java program to avoid NullPointerException
    // using Optional Class
      
    import java.util.Optional;
      
    public class Example {
        public static void main(String[] args)
        {
      
            // Create a String of size 10
            String[] a = new String[10];
      
            // Create an Optional Class instance
            // and get the state for a[1] element
            // for Null value
            Optional<String> check = Optional.ofNullable(a[1]);
      
            // If the value in the current instance is null,
            // it will return false, else true
            if (check.isPresent()) {
      
                // The String is empty
                // So a[1] will have null at present
                String upcase = a[1].toUpperCase();
                System.out.print(upcase);
            }
            else
      
                // As the current value is null
                System.out.println("String value is not present");
        }
    }

    chevron_right

    
    

    Output:

    String value is not present
    

    Note: Hence this can be understood as an exception handling method for NullPointerException

    NullPointerException Handling using Optional class:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java program to handle NullPointerException
    // using Optional Class
      
    import java.util.Optional;
      
    public class Example {
        public static void main(String[] args)
        {
      
            // Create a String of size 10
            String[] a = new String[10];
      
            // Define the a[1] element
            a[1] = "geeksforgeeks";
      
            // Create an Optional Class instance
            // and get the state for a[1] element
            // for Null value
            Optional<String> check = Optional.ofNullable(a[1]);
      
            // If the value in the current instance is null,
            // it will return false, else true
            if (check.isPresent()) {
      
                // The String is not empty
                // So a[1] will have a value at present
                String upcase = a[1].toUpperCase();
                System.out.print(upcase);
            }
            else
      
                // If the current value is null
                System.out.println("String value is not present");
        }
    }

    chevron_right

    
    

    Output:

    GEEKSFORGEEKS
    


    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



    Improved By : SohomPramanick