Java Tutorials

Java Optional Class

Java Optional class can handle NullPointerExceptions as well as in java 8 Stream API is empty, some of the intermediate or terminal functions returns Optional reference Object

      Java Optional Class is a reference Type, Assigning a null value to Optional object, is an error.

Optional Class located in java.util package

Other Optional Classes
  • OptionalInt
  • OptionalLong
  • OptionalDouble

Creating a Optional Class

     You can not create a Optional object using a new Operator.But Optional class provides factory methods to create an object of it. These are the following methods used to create an Optional Object.

Difference between of and ofNullable, if value is null , former throws an Exception. later doesnt throw an Exception


	Optional<String> opt = Optional.empty();
	String str =  null;
	Optional<String> opt = Optiona.of(str);  //throws an Exception
	better to deal above case using ofNullable method.
	Optional<String> opt = Optional.ofNullable(str);

Accessing a Value from Optional Object

     Accessing a value from Optional Object first needs to check is value present using isPresent() method ,true means value exists then call get method

. Directly accessing a value using get method may throw an Exception.
Note: value means other than non-null or empty
	String str = "Text Message";
	Optional<String> opt = Optional.ofNullable(str);
	//Alwyas Check if non-null value present in Optional Object. using isPresent method
	//then call get method
	if( opt.isPresent() ) System.out.println( opt.get() );

Usage of Optional.of and Optional.isNullable methods of Optional Class

      getMobileNo method returns Optional<String> object, in function body, checks given string has 10-digit mobile number, if exists

mobile number as a string,passed to Optional.of(no) method


null value using Optional.ofNullable(null)

Optional<String> getMobileNo(String no){

   	 if( no.matches( "Phone:(\\d){10}") )
   	     return Optional.of(no.replace("Phone:",""));
    	   return Optional.ofNullable(null);

Calling above function

   mobile number passed to getMobileno() method, returns Optional object. In order to access value from Optional object, if value present using isPresent then call get method, otherwise get method throws NoSuchElementException Exception.
Note: Used ternery Operator to access a value.

	String no = "Phone:8767896666";
	Optional<String> optional = getMobileNo(no);
	String phone = (optional.isPresent())?optional.get():"NOT FOUND";

In above code used terneray operator to get a value , if value not found returns "NOT FOUND". terneray operator can be replaced with orElse method as shown below

	System.out.println( optional.orElse("NOT FOUND") );

ifPresent method

    ifPresent method ,if value presents invokes specified consumer interface, returns nothing. Note: Consumer interfaces takes input values, processes it, returns nothing.

ifPresent syntax:
	ifPresent(Consumer<? super T> consumer)

Consumer interface can be used to format the given Phone number.

opt.ifPresent( (s)->System.out.println(s.substring(0,3)+"-"+s.substring(3,6)+"-"+s.substring(6,10)))
Consumer interface can be implemented using Method Reference. We have a class called Formatter, which has method called Format,accpets input param String Class Formatter
class Formatter
      static void format(String str){
         System.out.println( str.substring(0,3)+"-"+str.substring(3,6)+"-"+str.substring(6,10));

Calling ifPresent method using Method reference

optional.ifPresent(  Formatter::format );