Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at the demonstration of Optional<T> class in Java 8.
Optional is introduced in Java 8 mainly to provide a way to avoid Null Pointer Exceptions in the code. Instead of directly working on probably a null returning value, it’s better to use Optional instance to avoid NullPointerException. You can find the complete documentation here.
- Optional class doesn’t have any constructors.
- isPresent() method is used to check if the instance has a value.
- get() method is used to retrieve the value. it will throw “NoSuchElementException” if there is no value.
- of(T val) method is used to create Optional<T> instance – val must be a non-null value.
- ofNullable(T val) method is used to create Optional<T> instance – if val is null, it returns an empty Optional.
- orElse(T defaultVal) method is used to return T if present, otherwise it returns defaultVal
Let’s look at a sample program:
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
package com.clearurdoubt; import java.util.List; import java.util.ArrayList; import java.util.Optional; /** * @author Sai Gowtham Badvity * Demo of Optional class * */ public class OptionalClassDemo { public static void main(String[] args) { // Let's create a List of Strings List<String> list = new ArrayList<>(); // Add one null entry list.add("One"); list.add("Two"); list.add(null); list.add("Three"); // Declare an Optional<String> instance Optional<String> opt; System.out.println("Items in the list: "); // loop through the list for(String str : list) { // retrieve the Optional<String> class instance from the current String opt = Optional.ofNullable(str); // Print a default value if the current value is null System.out.print(opt.orElse("default") + " "); } // Few more scenarios Optional<String> optTest1 = Optional.empty(); // returns an empty Optional instance Optional<String> optTest2 = Optional.of("Optional Class Test"); // "of()" is used only if the value is not null else it's better to use "ofNullable()" // check optTest1 if(optTest1.isPresent()) // isPresent() return true if it has a value else returns false System.out.println("\n\noptTest1 has value."); else System.out.println("\n\noptTest1 has no value. Default value is : " + optTest1.orElse("DEFAULT")); // check optTest2 if(optTest2.isPresent()) System.out.println("\noptTest2 = " + optTest2.get()); // get() is used to retrieve the value. NoSuchElementException is thrown if there is no value. else System.out.println("\noptTest2 has no value."); } } |
Output:
Happy Learning :).
Please let me know in case of any queries.