GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Java Tutorial
  • Advanced Java
  • Interview Questions
  • Exercises
  • Examples
  • Quizzes
  • Projects
  • Cheatsheet
  • DSA in Java
  • Java Collection
  • Optional.empty()
  • Optional.of(value)
  • Optional.ofNullable(value)
  • Introduction3 min read

This view

  • Original page
  • New address

GeezerVison is showing www.geeksforgeeks.org — Java 8 Optional Class - GeeksforGeeks

geeksforgeeks
search icon
  • Courses
  • Tutorials
  • Interview Prep
  • Java Tutorial
  • Advanced Java
  • Interview Questions
  • Exercises
  • Examples
  • Quizzes
  • Projects
  • Cheatsheet
  • DSA in Java
  • Java Collection

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

Explore

    Basics
    • Introduction3 min read
    • Variables2 min read
    • Data Types7 min read
    • Operators7 min read
    • Decision Making5 min read
    • Methods7 min read
    • Arrays7 min read
    • Strings5 min read
    OOP & Interface
    • Introduction6 min read
    • Constructors6 min read
    • Encapsulation3 min read
    • Inheritance8 min read
    • Polymorphism5 min read
    • Abstraction5 min read
    • Interfaces8 min read
    Collections
    • Collection class9 min read
    • Collection Interface5 min read
    • List Interface8 min read
    • Set Interface5 min read
    • Queue Interface5 min read
    • Map Interface in Java6 min read
    • Iterator4 min read
    Advance Java Concepts
    • Exception handling6 min read
    • Java Multithreading Tutorial3 min read
    • Synchronization in Java9 min read
    • File handling6 min read
    • Method References3 min read
    • Java 8 Stream Tutorial7 min read
    • Memory Management4 min read
    • Garbage Collection in Java6 min read
    • Networking6 min read
    • JDBC5 min read
    Practice Java
    • Interview Questions15+ min read
    • Programs6 min read
    • Practice Problems5 min read
    • Quiz1 min read
    • Project Ideas15+ min read
    Courses
    • Java Backend Course2 min read
    • Placement 360 Course2 min read
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.