Updated May 2, 2023
Introduction to Optional Class in Java 8
In java 8(jdk8), java introduces a new class optional class, which is used to void NullPointerException in Java. The NullPointerException can crash the code and it is hard to avoid it without performing many null checks, but by using optional class in a program we can easily check whether a variable contains a null value or not and avoid the NullPointerException. With the help of an Optional class, we can provide alternate code to run or alternate values to return. As the optional class is a built-in class in java.util package.
Syntax:
public final class Optional<T> extends Object
{
// code of the optional class
}
As in the above syntax, the optional class is a final class which means that optional class cannot be extended and it is a generic class.
Member Functions of the Optional Class with Syntax
Member functions of the optional class are given below:
1. empty(): This function gives an empty Optional instance(Without any value in it).
public static <T> Optional<T> empty()
2. of(T value): This function gives an Optional instance(with the given non-null value).
public static <T> Optional<T> of( T value )
3. ofNullable(T value): This function gives an Optional instance(with the given value, if non-null, else an empty Optional.
public static <T> Optional<T> ofNullable(T value)
4. get(): This function gives the optional value if the value is present, else NoSuchElementException throws.
public T get()
5. isPresent(): This function gives true if the value is present in an Optional instance, otherwise false.
public boolean isPresent()
6. ifPresent(Consumer<? super T> consumer): This function invokes the given consumer with the specified value if a value is present, otherwise nothing performs.
public void ifPresent(Consumer<? super T> consumer)
7. filter(Predicate<? super T> predicate): This function returns an Optional instance with a given value if a value is present and that matches the specified predicate, otherwise empty Optional returns.
public Optional<T> filter(Predicate<? super T> predicate).
8. map(Function<? super T,? extends U> mapper): This function returns an Optional with the specified value if the value is there, and after applying the specified mapping function the give is non-null. Otherwise empty Optional returns.
public <U> Optional<U> map(Function<? super T,? extends U> mapper)
9. flatMap(Function<? super T,Optional<U> mapper): This function returns an Optional with a specified value if a value is present and after applying the specified optional mapping function the result is non-null. Otherwise empty Optional returns.
public <U> Optional<U> flatMap(Function<? super T,Optional<U> mapper)
10. orElse( T other ): This function gives the value, if it is present, otherwise give others.
public T orElse(T other)
11. orElseGet(Supplier<? extends T> other): This function gives the value if it is there, else others will invoke and return its result.
public T orElseGet(Supplier<? extends T> other)
12. orElseThrow(Supplier <? extends C> excepSupplier ) throws C extends Throwable: This function gives the present value, if it is there, else throws the provided supplier created an exception.
public <C extends Throwable> T orElseThrow(Supplier<? extends C> exceptionSupplier) throws C extends Throwable
13. equals( Object ob ): This function returns true if given ob object is equal to this Optional object. Otherwise, return false. The ob object can be equal if it is Optional or both objects have no value present or both objects present equal value.
public boolean equals(Object ob )
14. hashCode(): This function gives the hash code if the value is present, else return 0.
public int hashCode()
15. toString(): This function gives a string format presentation of an Optional object, this presentation may be different based on the versions and implementations.
public String toString()
Examples of Optional Class in Java
Next, we write the java code to understand how null value is present in a variable when we do not initialize the variable with the following example where we without using Optional class to avoid null value, as below –
Example #1
Code:
package p1;
public class Demo
{
public static void main( String[] arg)
{
String[] info = new String[5];
info[0]="John";
info[2]=new Integer(26).toString();
info[3]=info[0].substring(0)+" "+info[1].substring(0);
// display full infor
System.out.println("All present values are :");
System.out.println("fname : "+info[0]);
System.out.println("lname : "+info[1]);
System.out.println("Age : "+info[2]);
System.out.println("fullname: "+info[3]);
}
}
Output:
As in the above code, an Optional class is not used, so when we run the above program it throws a nullPointerException and terminates abnormally.
Next, we write the java code to understand optional class where we using Optional class to avoid abnormal termination, as below –
Example #2
Code:
package p1;
import java.util.Optional;
import java.util.Scanner;
public class Demo
{
public static void main( String[] arg)
{
Scanner sc= new Scanner(System.in);
String[] info = new String[5];
info[0]="John";
info[2]=new Integer(26).toString();
Optional<String> isNullfname = Optional.ofNullable(info[0]);
Optional<String> isNulllname = Optional.ofNullable(info[1]);
Optional<String> isNullage = Optional.ofNullable(info[2]);
for(int i=0; i<2;i++)
{
if(isNulllname.isPresent())
{
info[3]=info[0].substring(0)+" "+info[1].substring(0);
// display full infor
System.out.println("All present values are :");
System.out.println("fname : "+info[0]);
System.out.println("lname : "+info[1]);
System.out.println("Age : "+info[2]);
System.out.println("fullname: "+info[3]);
break;
}else
{
System.out.println("Last name is not present");
}
System.out.println("Enter last name");
info[1]=sc.next();
isNulllname = Optional.ofNullable(info[1]);
}
}
}
Output:
An in the above code an Optional class is used to avoid a nullPointerExceptionand the abnormal termination, so the code executes without crashing. And when the value is provided or presents it just printing the values.
Next, we write the java code to use all optional class functions, as below –
Example #3
Code:
package p1;
import java.util.Optional;
public class Demo
{
public static void main( String[] arg)
{
String[] info = new String[5];
info[0]="John";
info[2]=new Integer(26).toString();
Optional<String> e = Optional.empty();
Optional<String> v=Optional.ofNullable(info[0]);
Optional<String> val = Optional.of(info[0]);
System.out.print("\nempty() = "+e);
System.out.print("\nofNullable(info[0]) = "+v);
System.out.print("\nofvalue(info[0]) = "+val);
Optional<String> v1=Optional.ofNullable(info[1]);
//Optional<String> val1 = Optional.of(info[1]); throw exception
System.out.print("\nofNullable(info[1]) = "+v1);
System.out.print("\nhashCode()= "+val.hashCode());
System.out.print("\nfilter.equals(\"Joseph\") ="+val.filter((st)->st.equals("Joseph")));
System.out.print("\nFilter.equals(\"John\") ="+val.filter((st)->st.equals("John")));
System.out.print("\nget()= "+val.get());
System.out.print("\nispresent() = "+val.isPresent());
System.out.print("\nval.orElse(\"Value is not present\") = "+val.orElse("Value is not present"));
System.out.print("\ne.orElse(\"Value is not present\") = "+e.orElse("Value is not present"));
System.out.print(val.orElseGet(() -> "\nElse Default Value"));
System.out.print(e.orElseGet(() -> "\nElse Default Value"));
System.out.println(val.map(String::toUpperCase));
System.out.println(e.map(String::toUpperCase));
}
}
Output:
Recommended Articles
This is a guide to Optional Class in Java 8. Here we also discuss the function and working of optional class in java 8 along with different examples and its code implementation. You may also have a look at the following articles to learn more –