In the post Java 8 Optional Example, you’re introduced how to use the new java.util.Optional class. It is a public final class and used to deal with NullPointerException in Java application.
What is the Type of Null?
There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type. For example, field members of objects are automatically initialized to null and programmers typically initialize reference types to null when they don’t have an initial value to give them and, in general, null is used everytime where we don’t know or we don’t have a value to give to a reference.
What is wrong with just returning null?
For the ones that do not know what a NullPointerException is, just try:
1 2 3 4 5 6 7 8 9 10 |
public class Java8OptionalDemo { public static void main(String[] args) { String strOfNull = null; System.out.println(strOfNull.contains("123")); } } |
The code above would compile but you would get a warning like this:
1 |
Null pointer access: The variable strOfNull can only be null at this location |
In order to handle this problem, you can check and validate for null, or you can surround the block with a try catch. In Java 8, you can handle this issue using the new Optional class.
Java 8 Optionals
a) Creating Optional objects
In order to create an Optional we have to indicate what type of value is going to contain. There are 3 major ways to create an Optional, here.
*) Create empty optional using Optional.empty().
1 |
Optional<String> possible = Optional.empty(); |
*) Using Optional.of() to create optional with default non-null value.
1 |
Optional<String> possible = Optional.of(123); //If you pass null in of(), then a NullPointerException is thrown immediately. |
*) Using Optional.ofNullable() to create an Optional object that may hold a null value.
1 2 3 |
Optional<String> possible = Optional.ofNullable(null);//the resulting Optional object would be empty () //or Optional<String> possible = Optional.ofNullable(123); |
b) Java Optional Example: If Value is not Present
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class Java8OptionalDemo2 { public static void main(String[] args) { String strOfNull = null; Optional<String> checkNull = Optional.ofNullable(strOfNull); if(checkNull.isPresent()){ // check for value is present or not System.out.print(strOfNull); }else System.out.println("If the Optional object were empty, nothing would be printed."); } } |
Ouput should be printed like this
1 |
If the Optional object were empty, nothing would be printed. |
c) Java Optional Example: If Value is Present
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class Java8OptionalDemo3 { public static void main(String[] args) { Optional<String> strOfNull = Optional.of("If Value is Present"); if (strOfNull.isPresent()) { // check for value is present or not System.out.println(strOfNull.get()); } else System.out.println("If the Optional object were empty, nothing would be printed."); // Or other printer strOfNull.ifPresent(System.out::println); } } |
Ouput should be printed like this
1 2 |
If Value is Present If Value is Present |
d) Java Optional Methods Example: filter; hashCode; ofNullable; orElse methods
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class Java8OptionalDemo4 { public static void main(String[] args) { String str = "Java 8 Optional"; // It returns an empty instance of Optional class Optional<String> empty = Optional.empty(); System.out.println(empty); // It returns a non-empty Optional Optional<String> val = Optional.of(str); // If value is present, it returns an Optional otherwise returns an empty Optional System.out.println("Filtered value: "+val.filter((s)->s.equals("123"))); System.out.println("Filtered value: "+val.filter((s)->s.equals("Java 8 Optional"))); // It returns value of an Optional. if value is not present, it throws an NoSuchElementException System.out.println("Getting value: "+val.get()); // It returns hashCode of the value System.out.println("Getting hashCode: "+val.hashCode()); // It returns true if value is present, otherwise false System.out.println("Is value present: "+val.isPresent()); // It returns non-empty Optional if value is present, otherwise returns an empty Optional System.out.println("Nullable Optional: "+Optional.ofNullable(str)); // It returns value if value is present, otherwise returns specified value, System.out.println("orElse: "+val.orElse("Value is not present")); System.out.println("orElse: "+empty.orElse("Value is not present")); val.ifPresent(System.out::println); // print value by using method reference } } |
Ouput should be printed like this
Conclusion
Using Optional that helps to reduce the number of null pointer exceptions and the overall number of bugs in Java application. The purpose of Optional is not to avoid all types of null pointers
That’s all for Java 8 Optional Example.
Download complete source code, click link below
Java8OptionalExample.zip (217 downloads)