Open In App

Java 8 Optional Class

Last Updated : 29 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Optional is a container class introduced in Java 8 to represent optional (nullable) values. It is used to avoid NullPointerException by providing methods to check whether a value is present or not and handle it safely. By using Optional, we can specify alternate values to return or alternate code to run. This makes the code more readable because the facts that were hidden are now visible to the developer.

Example: Java program without 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

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.

Method

Description

empty()

Returns an empty Optional instance

of(T value)

Returns an Optional with the specified present non-null value.

ofNullable(T value)

Returns an Optional describing the specified value if non-null, else empty

equals(Object obj)

Checks if another object is "equal to" this Optional.

filter(Predicate<? super T> predicate)

If a value is present and matches the predicate, returns an Optional with the value; else returns empty.

flatMap(Function<? super T, Optional<U>> mapper)

If a value is present, applies a mapping function that returns an Optional; otherwise returns empty.

get()

Returns the value if present, else throws NoSuchElementException.

hashCode()

Returns the hash code of the value if present, otherwise returns 0.

ifPresent(Consumer<? super T> consumer)

Returns true if a value is present, else false.

map(Function<? super T, ? extends U> mapper)

If a value is present, applies the mapping function and returns an Optional describing the result (if non-null).

orElse(T other)

Returns the value if present, otherwise returns the provided 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 an exception provided by the supplier

toString()

Returns a non-empty string representation of this Optional for debugging.

Example 1 : Java program to illustrate some optional class methods.

Java
import java.util.Optional;

class GFG {

    // Driver code
    public static void main(String[] args)
    {

        // creating a string array
        String[] str = new String[5];

        // Setting value for 2nd index
        str[2] = "Geeks Classes are coming soon";

        // It returns an empty instance of Optional class
        Optional<String> empty = Optional.empty();
        System.out.println(empty);

        // It returns a non-empty Optional
        Optional<String> value = Optional.of(str[2]);
        System.out.println(value);
    }
}

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

Example 2 : Java program to illustrate some optional class methods

Java
import java.util.Optional;

class GFG {

    // Driver code
    public static void main(String[] args)
    {

        // creating a string array
        String[] str = new String[5];

        // Setting value for 2nd index
        str[2] = "Geeks Classes are coming soon";

        // It returns a non-empty Optional
        Optional<String> value = Optional.of(str[2]);

        // It returns value of an Optional.If value is not present, it throws an NoSuchElementException
        System.out.println(value.get());

        // It returns hashCode of the value
        System.out.println(value.hashCode());

        // It returns true if value is present, otherwise false
        System.out.println(value.isPresent());
    }
}

Output
Geeks Classes are coming soon
1967487235
true

Article Tags :
Practice Tags :

Similar Reads