Java 8 Optional Class

In Java 8, we have a newly introduced Optional class in java.util package. This class is introduced to avoid NullPointerException that we frequently encounters if we do not perform null checks in our code. Using this class we can easily check whether a variable has null value or not and by doing this we can avoid the NullPointerException. In this guide, we will see how to work with Optional class and the usage of various methods of this class.

Before we see the example of Optional class, let’s see what happens when we don’t use Optional class and do not perform null check.

Java Example: Without using Optional class

In this example, we didn’t assign the value to the String str and we are trying to get the substring out of it. Since there is no value present in the str, the program is throwing NullPointerException.

public class Example {
public static void main(String[] args) {
String[] str = new String[10];
//Getting the substring
String str2 = str[9].substring(2, 5);
//Displaying substring
System.out.print(str2);
}
}

%d bloggers like this: