Java 8 - Optional Class

Introduction

 
With the brief introduction in one of the previous articles, we have a brief knowledge of what the optional class includes. It is included in the new version of Java and is added to the Java. util package.
 
A final and value-based class named as Optional class is introduced with new versions of Java. As it provides an easier way to avoid NullPointerException, it helps in removing too many null checks, thus making the code more readable. By using the Optional Instance (a container object which may or may not contain a non-null value), we can specify alternate values to return or alternate code to execute.
 
Ways of using Optional Class:
  1. Get the value.
  2. Get if the object is Not Null, else Throw Exception.
  3. Get if the object is Not Null, else return default.
  4. Consume if it is Not Null.
Optional class is primarily intended for use as a method return type where there is a clear need to represent “no result” and where using null is likely to cause errors.
 

Optional Class

 
As mentioned above, the Optional class provides an easier way to avoid NullPointerException.
 
So when we declare reference variables and do not initialize them, a special value null is assigned to them.
 
Example
  1. package Optional_Class;  
  2. import java.util.Optional;  
  3. public class OptionalDemo {  
  4.     String name;  
  5.     public static void main(String[] args) {  
  6.         OptionalDemo opt = new OptionalDemo();  
  7.         Optional < String > n = Optional.ofNullable(opt.name);  
  8.         System.out.print(n.get());  
  9.     }  
  10. }  
The above example will result in returning “null” as output.
 
When we try to use a reference variable that is initialized with null and not holding a valid object, we end up with NullPointerException during runtime.
 
Example
  1. package Optional_Class;  
  2. import java.util.Optional;  
  3. public class OptionalDemo {  
  4.     String name;  
  5.     public static void main(String[] args) {  
  6.         OptionalDemo opt = new OptionalDemo();  
  7.         Char char = opt.name.charAt(0);  
  8.         System.out.print(char);  
  9.     }  
  10. }  
The above example will result in “NullPointerException” during runtime with the message as:
  1. Exception in thread "main" java.lang.NullPointerException at OptionalDemo.main(OptionalDemo.java:10).  

Methods in Optional class

 
To avoid Null checks during the program, here are the methods listed which are used under Optional class.
 
get() method
 
Syntax - public T get()
 
This method simply returns the object from an Optional instance. If a value is present, returns the value, else throws NoSuchElementException.
 
In the below example, no null check is done and the optional instance returns the contained value as it is. This will return an Optional instance with a present value if the specified value is not null, else an empty Optional instance.
 
Example
  1. package Optional_Class;  
  2. import java.util.Optional;  
  3. public class OptionalDemo {  
  4.     String name = "Csharp Corner";  
  5.     public static void main(String[] args) {  
  6.         OptionalDemo opt = new OptionalDemo();  
  7.         Optional < String > n = Optional.ofNullable(opt.name);  
  8.         System.out.print(n.get());  
  9.     }  
  10. }  
The above example will result in “Csharp Corner”, if we don’t initialize the variable, then the code is described as:
 
Example
  1. package Optional_Class;  
  2. import java.util.Optional;  
  3. public class OptionalDemo {  
  4.     String name;  
  5.     public static void main(String[] args) {  
  6.         OptionalDemo opt = new OptionalDemo();  
  7.         Optional < String > n = Optional.ofNullable(opt.name);  
  8.         System.out.print(n.get());  
  9.     }  
  10. }  
This will result in an exception with the message as:
  1. Exception in thread "main" java.util.NoSuchElementException: No value present at java.util.Optional.get(Optional.java:135) at OptionalDemo.main(OptionalDemo.java:11)  

orElseThrow() method

 
Syntax - public T orElseThrow()
 
This method returns the object value if the object value is not null. If a value is present, it returns the value, or else it throws the specified exception.
 
Example
  1. package Optional_Class;  
  2. import java.util.Optional;  
  3. public class OptionalDemo {  
  4.     String name = "Csharp Corner";  
  5.     public static void main(String[] args) {  
  6.         OptionalDemo opt = new OptionalDemo();  
  7.         Optional < String > n = Optional.ofNullable(opt.name);  
  8.         System.out.print(n.orElseThrow(NullPointerException::new));  
  9.     }  
  10. }  
The above example will result in “Csharp Corner” and here a custom exception is also used. If we don’t initialize the variable, then the code is described as:
 
Example
  1. package Optional_Class;  
  2. import java.util.Optional;  
  3. public class OptionalDemo {  
  4.     String name;  
  5.     public static void main(String[] args) {  
  6.         OptionalDemo opt = new OptionalDemo();  
  7.         Optional < String > n = Optional.ofNullable(opt.name);  
  8.         System.out.print(n.orElseThrow(NullPointerException::new));  
  9.     }  
  10. }  
This will result in an exception with the message as:
  1. Exception in thread "main" java.util.NullPointerException at java.util.Optional.orElseThrow(Optional.java:290) at OptionalDemo.main(OptionalDemo.java:11)  

orElseThrow() method

 
Syntax - public T or Else​(T other)
 
Here, the other is a value to be returned and T is the return type of the returned value.
 
This method returns the object value if the object value is not null. If a value is present, returns the value, else returns the given default value.
 
Example
  1. package Optional_Class;  
  2. import java.util.Optional;  
  3. public class OptionalDemo {  
  4.     String name = "Csharp Corner";  
  5.     String default_name = "C# Corner";  
  6.     public static void main(String[] args) {  
  7.         OptionalDemo opt = new OptionalDemo();  
  8.         Optional < String > n = Optional.ofNullable(opt.name);  
  9.         System.out.print(n.orElse(opt.default_name));  
  10.     }  
  11. }  
The above example will result in “Csharp Corner” and if we don’t initialize the variable “name” with some value then the code is described as:
 
Example
  1. package Optional_Class;  
  2. import java.util.Optional;  
  3. public class OptionalDemo {  
  4.     String name;  
  5.     String default_name = "C# Corner";  
  6.     public static void main(String[] args) {  
  7.         OptionalDemo opt = new OptionalDemo();  
  8.         Optional < String > n = Optional.ofNullable(opt.name);  
  9.         System.out.print(n.orElse(opt.default_name));  
  10.     }  
  11. }  
This will not result in an exception else returns a default name as C# Corner here.
 

isPresent() method

 
Syntax - public boolean is Present()
 
As the method suggests it will return a boolean value, this method returns the object value if the object value is not null, else returns false.
 
Example
  1. package Optional_Class;  
  2. import java.util.Optional;  
  3. public class OptionalDemo {  
  4.     String name = "Csharp Corner";  
  5.     public static void main(String[] args) {  
  6.         OptionalDemo opt = new OptionalDemo();  
  7.         Optional < String > n = Optional.ofNullable(opt.name);  
  8.         if (n.isPresent()) {  
  9.             System.out.print(n.get());  
  10.         } else {  
  11.             System.out.print("Null Value");  
  12.         }  
  13.     }  
  14. }  
The above example will result in “Csharp Corner” and if we don’t initialize the variable “name” with some value then the code is described as:
 
Example
  1. package Optional_Class;  
  2. import java.util.Optional;  
  3. public class OptionalDemo {  
  4.     String name;  
  5.     public static void main(String[] args) {  
  6.         OptionalDemo opt = new OptionalDemo();  
  7.         Optional < String > n = Optional.ofNullable(opt.name);  
  8.         if (n.isPresent()) {  
  9.             System.out.print(n.get());  
  10.         } else {  
  11.             System.out.print("Null Value");  
  12.         }  
  13.     }  
  14. }  
This will not result in an exception and returns a name as “Null Value”.
 

ifPresent() method

 
Syntax - public void if Present​(Consumer<? super T> action)
 
Here, the action is a parameter that defines the action to be performed and takes an input of type consumer (refer to here).
 
In this method, if a value is present, invoke a specific consumer else do nothing. In other words, if the value is present, perform the action with a given value, else do nothing.
 
It returns a NullPointerException if the given action is null.
 
Example
  1. package Optional_Class;  
  2. import java.util.Optional;  
  3. public class OptionalDemo {  
  4.     String name = "Csharp Corner";  
  5.     public static void main(String[] args) {  
  6.         OptionalDemo opt = new OptionalDemo();  
  7.         Optional < String > n = Optional.ofNullable(opt.name);  
  8.         n.ifPresent(System.out::println); //Method Reference  
  9.     }  
  10. }  
The above example will result in “Csharp Corner”, if we don’t initialize the variable then the code is described as:
 
Example
  1. package Optional_Class;  
  2. import java.util.Optional;  
  3. public class OptionalDemo {  
  4.     String name;  
  5.     public static void main(String[] args) {  
  6.         OptionalDemo opt = new OptionalDemo();  
  7.         Optional < String > n = Optional.ofNullable(opt.name);  
  8.         n.ifPresent(System.out::println); //Method Reference  
  9.     }  
  10. }  
This will print nothing to the console window.
 
What did we learn?
 
After reading this article, users have a thorough knowledge of what Optional Class and their usage with existing Java versions.
 
Note
Optional class is primarily intended for use as a method return type where there is a clear need to represent “no result” and where using null is likely to cause errors.
While trying to work with any feature of Java 8, remember to use JDK 1.8 or higher, or else these concepts and code will not work.
 

Summary

 
As discussed above, we have learned the following:
  1. What is the Optional class?
  2. Why the Optional class?
  3. Methods in Optional class.
For more related topics of Java 8:
  • Introduction to Java 8 here.
  • Functional Interfaces here.
  • Lambda Expressions here.
  • Stream API here.
  • Stream Vs Collection here.