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 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.
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 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.
Optional is a generic type of type T. Optional<T>
Rectifying the code for the above NullPointerException using Optional Class:
String value is not present
Note: Hence this can be understood as an exception handling method for NullPointerException
NullPointerException Handling using Optional class: