Last Updated: 18 November, 2023
Optional is a public and final class in Java; it was introduced in the Java 8 version and is available in the java.util package.
Optional class is used to deal with NullPointerException in Java applications and helps in writing neat code without using too many null check conditions.
The Optional class provides various methods for checking whether a variable has a null value or not, and by doing this, we can avoid the NullPointerException at runtime.
Class declaration:
Optional is a generic class that accept a type parameter T. In addition, it uses the final modifier, which prevents other classes from inheriting it.
Optional class provides a type-level solution for representing optional values instead of null references.
Let's see an example below where we are not using the Optional class in the program, so during execution, the program terminates abnormally and throws a NullPointerException.
Example 1: Java Program without using Optionl class.
Output
Exception in thread "main" java.lang.NullPointerException at com.javabytechie.optional.ProgramWithoutOptinal.main(ProgramWithoutOptinal.java:7)
Optional class is used to prevent unexpected program termination. We'll use Optional in the following example.
Example 2: Java Program with using Optionl class.
Output
string value is not present
The Optional class contains both static and instance methods. Static methods are called using the Option class name; to invoke an instance method, we need to create an instance of the Optinal class.
First, let's see all the static methods of the Optional class in the given table below.
Methods | Descriptions |
public static <T> Optional<T> empty() | This method will return an empty Optional instance. |
public static <T> Optional<T> of(T value) | It returns an Optional with the specified present non-null value. Throws NullPointerException if the value is null. |
public static <T> Optional<T> ofNullable(T value) | It returns an Optional describing the specified value if it is non-null; otherwise, it returns an empty Optional. |
There are the following instance methods of the Optional class in Java.
Methods | Description |
public T get() | If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException. |
public boolean isPresent() | It returns true if there is a value present, otherwise false. |
public void ifPresent(Consumer<? super T> consumer) | If a value is present, invoke the specified consumer with the value, otherwise do nothing. |
public Optional<T> filter(Predicate<? super T> predicate) | If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional. |
public <U> Optional<U> map(Function<? super T,? extends U> mapper) | If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional. |
public <U> Optional<U> flatMap(Function<? super T,Optional<U> mapper) | If a value is present, apply the provided Optional-bearing mapping function to it, return that result, otherwise return an empty Optional. |
public T orElse(T other) | It returns the value if present, otherwise returns other. |
public T orElseGet(Supplier<? extends T> other) | It returns the value if present, otherwise invoke other and return the result of that invocation. |
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X extends Throwable | It returns the contained value, if present, otherwise throw an exception to be created by the provided supplier. |
public boolean equals(Object obj) | Indicates whether some other object is "equal to" this Optional or not. |
public int hashCode() | It returns the hash code value of the present value, if any, or returns 0 (zero) if no value is present. |
public String toString() | Returns a non-empty string representation of this Optional suitable for debugging. |
There are some examples given; let's see and understand the uses of each method of the Optionl class in a Java program.
The empty() method is a static method; it returns an empty Optional instance.
Output
Optional.empty
The of() is a static method; it returns an Optional with the specified present non-null value. This method will throw a NullPointerException if the value is null.
Output
Optional[JavaByTechie]
Exception in thread "main" java.lang.NullPointerException
at java.util.Objects.requireNonNull(Objects.java:203)
at java.util.Optional.<init>(Optional.java:96)
at java.util.Optional.of(Optional.java:108)
at com.javabytechie.optional.OptionalExample2.main(OptionalExample2.java:10)
The ofNullable() is a static method; it returns an Optional describing the specified value, if non-null; otherwise, it returns an empty Optional.
Output
Optional[JavaByTechie]
Optional.empty
The isPresent() method returns true if there is a value present; otherwise, it returns false.
Output
emptyOptional.isPresent(): false
nonEmptyOptional.isPresent(): true
If a value is present and the value matches the given predicate, return an Optional describing the value; otherwise, return an empty Optional. This method will throw a NullPointerException if the predicate is null.
Output
Optional[JavaByTechie]
Optional.empty
Optional.empty
Optional[JavaByTechie]
If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise, return an empty Optional. This method will throw a NullPointerException if the mapping function is null.
Output
Optional.empty
Optional[javabytechie]
Optional.empty
If a value is present, apply the provided Optional-bearing mapping function to it, return that result, otherwise return an empty Optional. This method is similar to map(Function), but the provided mapper is one whose result is already an Optional, and if invoked, flatMap does not wrap it with an additional Optional. This method will throw NullPointerException if the mapping function is null or returns a null result.
Output
Optional[Optional[JavaB]]
Optional[JavaB]
Optional.empty
Output
JavaByTechie
Online Java Tutorial
Output
Core Java Tutorial
JavaByTechie
Output
JavaByTechie
Exception in thread "main" java.lang.NullPointerException
at java.util.Optional.orElseThrow(Optional.java:290)
at com.javabytechie.optional.OptionalExample10.main(OptionalExample10.java:13)
Note: Optional class is not meant to replace null checks or exceptions in all situations. It is especially helpful when a value might not be there, but that is an expected situation that needs to be dealt with. Optional can make code easier to read and more expressive by making it clearer when a value is not present and by letting functional actions be chained together.
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Optional
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com