Java 8 Optional Class

Last Updated : 1 Oct, 2026

Java 8 introduced the Optional class to represent a value that may or may not be present. It provides a clear way to handle missing values instead of relying directly on null.

  • Provides methods to check, retrieve, transform, or provide alternatives for a value.
  • Encourages explicit handling of potentially absent values.

Why Do We Need Optional?

Using null to represent a missing value requires explicit null checks. If these checks are missed, accessing the value can result in a NullPointerException. Optional makes the possibility of an absent value explicit and provides methods for handling both present and empty cases.

Example: Program Without the Optional Class

Java
public class OptionalDemo {
    public static void main(String[] args)
    {
        String[] words = new String[10];
        String word = words[5].toLowerCase();
        System.out.print(word);
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException

To avoid abnormal termination, we use the Optional class. In the following example, we are using Optional. So, our program can execute without crashing.

Example: Program using Optional Class

Java
import java.util.Optional;

// Driver Class
public class OptionalDemo {
      // Main Method
    public static void main(String[] args)
    {
        String[] words = new String[10];
        
          Optional<String> checkNull = Optional.ofNullable(words[5]);
        
          if (checkNull.isPresent()) {
            String word = words[5].toLowerCase();
            System.out.print(word);
        }
        else
            System.out.println("word is null");
    }
}

Output
word is null

Creating Optional Objects

The Optional class provides factory methods to create objects based on whether a value is available or may be absent.

  • Optional.empty(): Creates an Optional that contains no value.
  • Optional.of(value): Creates an Optional with a non-null value. It throws NullPointerException if the value is null.
  • Optional.ofNullable(value): Creates an Optional containing the value if it is non-null; otherwise, returns an empty Optional.

Example 1: Using empty() and of()

Java
import java.util.Optional;

class GFG {
    public static void main(String[] args) {
        String[] str = new String[5];
        str[2] = "Geeks Classes are coming soon";

        Optional<String> empty = Optional.empty();
        System.out.println(empty); 

        Optional<String> value = Optional.of(str[2]);
        System.out.println(value); 
    }
}

Output
Optional.empty
Optional[Geeks Classes are coming soon]

Explanation: In this example, Optional.empty() creates an Optional object with no value. Then, Optional.of(str[2]) creates an Optional that contains a non-null string. The print statements display an empty Optional and an Optional holding a value, showing how Optional safely represents both cases.

Example 2: Using get(), hashCode() and isPresent()

Java
import java.util.Optional;

class GFG {
    public static void main(String[] args) {
        String[] str = new String[5];
        str[2] = "Geeks Classes are coming soon";

        Optional<String> value = Optional.of(str[2]);

        System.out.println(value.get());       
        System.out.println(value.hashCode());  
        System.out.println(value.isPresent()); 
    }
}

Output
Geeks Classes are coming soon
1967487235
true

Explanation: Here, Optional.of(str[2]) stores a value inside the Optional object. The get() method retrieves that value, hashCode() returns its hash value, and isPresent() checks whether a value exists. Since the value is present, it returns true.

Common Methods in Optional

The Optional class offers methods such as isPresent() orElse() and ifPresent() to handle potentially null values more safely and functionally. The table below lists commonly used Optional methods and their descriptions.

MethodDescription
empty()Returns an empty Optional instance.
of(T value)Returns an Optional containing the specified non-null value.
ofNullable(T value)Returns an Optional containing the specified value if non-null; otherwise, returns an empty Optional.
equals(Object obj)Checks whether another object is equal to this Optional.
filter(Predicate<? super T> predicate)Returns the Optional if its value matches the given predicate; otherwise, returns an empty Optional.
flatMap(Function<? super T, Optional<U>> mapper)Applies the given mapping function if a value is present and returns its Optional result; otherwise, returns an empty Optional.
get()Returns the value if present; otherwise, throws NoSuchElementException.
hashCode()Returns the hash code of the value if present; otherwise, returns 0.
ifPresent(Consumer<? super T> consumer)Performs the given action if a value is present; otherwise, does nothing.
map(Function<? super T, ? extends U> mapper)Applies the given mapping function if a value is present and returns an Optional containing the mapped result if non-null.
orElse(T other)Returns the value if present; otherwise, returns the specified default value.
orElseGet(Supplier<? extends T> other)Returns the value if present; otherwise, invokes the supplier and returns its result.
orElseThrow(Supplier<? extends X> exceptionSupplier)Returns the value if present; otherwise, throws the exception supplied by the given supplier.
toString()Returns a string representation of the Optional, suitable for debugging.
Comment