Java 8 – Optionals

4 min read

Hey Guys!! In this post we will be learning a very useful concept of Java 8, that helped vastly in enhancing code readability.

Optionals was introduced as a part of Java 8 to represent non-null value. It helped in avoiding unnecessary Null checks and Null pointer exception. This feature is inspired from scala, groovy etc.

ofNullable(), empty(), of()

public class optionalExample {

    public static Optional<String> ofNullable(){

        Optional<String> stringOptional = Optional.ofNullable("Undeterministic String");
        //Optional<String> stringOptional = Optional.of(null); Optional.empty()
        return stringOptional;
    }

    public static Optional<String> of(){

        Optional<String> stringOptional = Optional.of("Undeterministic String");
       //Optional<String> stringOptional = Optional.of(null); Null pointer exception
        return stringOptional;
    }
    public static void main(String[] args) {
       System.out.println(ofNullable().get());
       System.out.println(ofNullable().isPresent());
       System.out.println(of().get());
    }
}

In the above example, we have demonstrated ofNullable() and of() methods in Optional. The difference between them is while handling null or non deterministic String object. ofNullable() returns Optional.empty() and of() throws a Null Pointer Exception.

orElse(), orElseGet(), orElseThrow()

OrElse: Execute logic and pass result as argument.

public T orElse(T other) {    
 return value != null ? value : other;
}

OrElseGet: Execute logic if value inside the optional is null.

public T orElseGet(Supplier<? extends T> other) {
  return value != null ? value : other.get(); 
}

The argument of “Optional.orElse” always gets executed irrespective of the value of the object in optional (null, empty or with value).

OrElseThrow:  This method returns the value of this Optional instance, if present. If there is no value present in this Optional instance, then this method throws the exception generated from the specified supplier.

optionalUsers.orElseThrow(() -> 
new UsernameNotFoundException("Username not found"));

ifPresent(), isPresent()

public class OptionalIsPresentExample {

    public static void main(String[] args) {
        
        //isPresent
        Optional<String> optional = Optional.ofNullable(" Hey Optional Object");
        System.out.println(optional.isPresent());
        
        if(optional.isPresent()){
            System.out.println(optional.get());
        }
        
        //ifPresent
        optional.ifPresent(s-> System.out.println(s));
    }
}

isPresent(): It checks whether there is any value in the Optional object. It returns Boolean values based on the presence of value.

ifPresent(): It takes a Consumer interface as an input. First, it checks whether an Optional has an value. If present, then we can consume those value and perform any operation on it.

Hope this will be helpful in understanding concept of optional. Keep reading.

Happy Learning!!