Another feature that Java 8 brought is Optional Class that is capable of representing null or non-null values. It can be defined as container object which provides a way of handling null check that prevents NullPointerException. It supports a bunch of utility methods such as isPresent(), filter(), empty(), get() and so on.
Points to remember:
– It is a final class that can handle null pointer exception while working with object.
– It comes under java.util.optional package.
– It is an efficient way of handling null checks that prevents NullPointerException.
– It produces concise code as it also helps us to avoid writing boilerplate codes(Bunch of if and else statements).
Some Important Methods
– isPresent() method identifies whether a value is there or not. It return false if it points to null value
– get() method is used to get values exist in Optional otherwise NoSuchElementException would be thrown
– orElse() : returns value if values are exist otherwise returns other
– empty() : Returns an empty Optional instance
– filter() : uses predicate to filter out undesired values
– map() : uses function to process logic over the given data
public class OpationalExample { public static void main(String[] args) { Integer[] arr = new Integer[1]; int num = arr[0]/10; System.out.println(num); } }
Error:
Exception in thread "main" java.lang.NullPointerException at OpationalExample.main(OpationalExample.java:9)
Explanation:
When we try to access an index position which simply doesn’t contain anything and try to perform operation on it, a runtime exception named NullPointerException is triggered. We can use Optional Class to deal with this problem.
import java.util.Optional; public class OpationalExample { public static void main(String[] args) { Integer[] arr = new Integer[1]; Optional<Integer > num = Optional.ofNullable(arr[0]); if(num.isPresent()) System.out.println("value :" +(num.get() /10)); else System.out.println("No value exist"); } }
Output:
No value exist