Java Optional Class

Su Suriya Ravichandran Updated 18 Nov 2026
9 min read ·Lesson 179 of 306

The Problem Optional Solves

Many methods sometimes have no result: a user lookup finds nobody, a search finds no match, a configuration key isn't set. Traditionally, Java methods return null in that case. The trouble is that nothing in the method's signature says so:

String email = findEmail("ravi");     // might be null — the type String doesn't tell you
email.toUpperCase();                  // NullPointerException if it was

Callers forget to check, and the program fails with a NullPointerException somewhere far from the cause. Tony Hoare, who introduced null references in 1965, later called them his "billion-dollar mistake".

java.util.Optional<T> (Java 8) is a container that holds either one value or nothing. A method that returns Optional<String> states in its signature that the result may be absent, and the Optional API makes the caller decide what to do in that case — use a default, throw an exception, skip an action — before getting at the value.

Optional<String> email = findEmail("ravi");
String address = email.orElse("no email");   // the absent case is handled explicitly

Creating and Reading Optionals

import java.util.*;

public class O1 {
    static final Map<String, String> EMAILS = Map.of("asha", "asha@gocourse.in");

    static Optional<String> findEmail(String user) {
        return Optional.ofNullable(EMAILS.get(user));
    }

    public static void main(String[] args) {
        Optional<String> a = Optional.of("Java");
        Optional<String> b = Optional.empty();
        Optional<String> c = Optional.ofNullable(null);
        System.out.println(a + " " + b + " " + c + " " + b.equals(c));
        try {
            Optional.of(null);
        } catch (NullPointerException e) {
            System.out.println("Optional.of(null): NullPointerException");
        }

        System.out.println(findEmail("asha").isPresent() + " " + findEmail("ravi").isEmpty());
        System.out.println(findEmail("asha").orElse("no email"));
        System.out.println(findEmail("ravi").orElse("no email"));
        try {
            findEmail("ravi").get();
        } catch (NoSuchElementException e) {
            System.out.println("get() on empty: NoSuchElementException " + e.getMessage());
        }
        try {
            findEmail("ravi").orElseThrow(() -> new IllegalArgumentException("user ravi has no email"));
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
        findEmail("asha").ifPresent(e -> System.out.println("sending to " + e));
        findEmail("ravi").ifPresentOrElse(e -> System.out.println("sending to " + e),
                                          () -> System.out.println("ravi: ask for an email first"));
    }
}

Output:

Optional[Java] Optional.empty Optional.empty true
Optional.of(null): NullPointerException
true true
asha@gocourse.in
no email
get() on empty: NoSuchElementException No value present
user ravi has no email
sending to asha@gocourse.in
ravi: ask for an email first

Creating

MethodUse when
Optional.of(value)The value is definitely not null — throws NullPointerException otherwise
Optional.ofNullable(value)The value may be null — gives an empty Optional for null
Optional.empty()There is no value

findEmail uses ofNullable because Map.get returns null for missing keys — this is the typical bridge from older, null-returning APIs.

Checking and getting the value

MethodBehaviour
isPresent() / isEmpty() (Java 11+)Whether a value is there
orElse(default)The value, or the default
orElseGet(supplier)The value, or a default computed only if needed
orElseThrow(exceptionSupplier)The value, or throw your exception
orElseThrow() (Java 10+)The value, or throw NoSuchElementException
get()Same as orElseThrow() — avoid it (see below)
ifPresent(consumer)Run an action only if there's a value
ifPresentOrElse(consumer, runnable) (Java 9+)One action for a value, another for absence

Avoid get(): optional.get() throws NoSuchElementException for an empty Optional, which is just a NullPointerException under another name. Code like if (opt.isPresent()) { use(opt.get()); } is legal but gains nothing over a null check. The methods that combine the check and the access — orElse, orElseThrow, ifPresent, map — express the intent directly. When you're certain a value exists, orElseThrow() says so explicitly.

orElse versus orElseGet

import java.util.*;

public class Lazy {
    static String expensiveDefault() {
        System.out.println("  (computing default...)");
        return "guest";
    }

    public static void main(String[] args) {
        Optional<String> name = Optional.of("asha");
        System.out.println("orElse:    " + name.orElse(expensiveDefault()));
        System.out.println("orElseGet: " + name.orElseGet(Lazy::expensiveDefault));
        System.out.println("empty orElseGet: " + Optional.<String>empty().orElseGet(Lazy::expensiveDefault));
    }
}

Output:

  (computing default...)
orElse:    asha
orElseGet: asha
  (computing default...)
empty orElseGet: guest

orElse(expensiveDefault()) is an ordinary method call: Java evaluates the argument before calling orElse, so the default is computed even though a value is present. orElseGet(supplier) only calls the supplier when the Optional is empty. Use orElse for constants and cheap values; use orElseGet when the default involves work — a database query, a remote call, creating a large object — or has side effects.

Transforming: map, flatMap and filter

Optional has map, flatMap and filter, which work like their stream counterparts on a "stream" of zero or one elements. They let you chain steps where any step may produce nothing, without nested null checks.

import java.util.*;

public class Chain {
    record Address(String street, String city, String pin) { }
    record Customer(String name, Address address, String phone) {
        Optional<Address> findAddress() { return Optional.ofNullable(address); }
    }

    static final Map<Integer, Customer> DB = Map.of(
        1, new Customer("Asha", new Address("12 Anna Salai", "Chennai", "600002"), "+91-90000-11111"),
        2, new Customer("Ravi", null, null),
        3, new Customer("Meena", new Address("4 Gandhi Rd", "madurai", "625001"), " "));

    static Optional<Customer> find(int id) { return Optional.ofNullable(DB.get(id)); }

    static String deliveryCity(int id) {
        return find(id)
            .flatMap(Customer::findAddress)
            .map(Address::city)
            .map(c -> c.substring(0, 1).toUpperCase() + c.substring(1))
            .orElse("(no address)");
    }

    static Optional<String> contactPhone(int id) {
        return find(id).map(Customer::phone).filter(p -> !p.isBlank());
    }

    public static void main(String[] args) {
        for (int id : new int[] {1, 2, 3, 4}) {
            System.out.printf("%d: city=%s, phone=%s%n", id, deliveryCity(id), contactPhone(id).orElse("-"));
        }
        System.out.println(find(1).map(Customer::findAddress));
        System.out.println(find(1).flatMap(Customer::findAddress).map(Address::pin));
    }
}

Output:

1: city=Chennai, phone=+91-90000-11111
2: city=(no address), phone=-
3: city=Madurai, phone=-
4: city=(no address), phone=-
Optional[Optional[Address[street=12 Anna Salai, city=Chennai, pin=600002]]]
Optional[600002]
MethodIf a value is presentIf empty
map(f)Applies f; returns Optional.ofNullable(result)Stays empty
flatMap(f)Applies f, which itself returns an Optional; returns thatStays empty
filter(p)Keeps the value if p is true, otherwise becomes emptyStays empty
or(supplier) (Java 9+)Keeps this OptionalReturns the Optional from the supplier
stream() (Java 9+)A one-element streamAn empty stream

How the lookups work:

  • deliveryCity chains four steps, each of which may come up empty: customer 4 doesn't exist, customer 2 has no address. Without Optional this would be three nested if (x != null) checks. Only at the end is the absence handled, with orElse.
  • map versus flatMap: findAddress already returns an Optional<Address>. With map, the result is wrapped a second time — Optional[Optional[Address[...]]], as the last-but-one line shows. flatMap takes the inner Optional as the result. Rule: use map when the function returns a plain value, flatMap when it returns an Optional.
  • map turns null into empty: Ravi's phone is null; map(Customer::phone) produces an empty Optional rather than an Optional containing null.
  • filter treats a blank phone number (Meena's " ") as absent.

Primitive Optionals

OptionalInt, OptionalLong and OptionalDouble hold primitive values without boxing. They're returned by primitive stream operations such as IntStream.max(), average() and findFirst(), and read with getAsInt(), orElse(...), orElseThrow(). They have fewer methods than Optional — no map, flatMap or filter.

Guidelines for Using Optional

Optional was designed for one main purpose: method return values that may be absent. Using it everywhere causes more problems than it solves.

DoDon't
Return Optional<T> from methods that may find nothing (findById, findFirst, lookups)Use Optional as a field type — it isn't Serializable, and a nullable field with an accessor returning Optional (like findAddress above) is the usual pattern
Handle absence with orElse, orElseGet, orElseThrow, map, ifPresentCall get() without being sure there's a value
Return an empty collection when there are no resultsReturn Optional<List<T>> — an empty list already means "none"
Accept plain parameters and overload or use defaultsUse Optional as a method parameter — callers then have to wrap values, and can still pass null
Return Optional.empty()Return null from a method declared to return Optional — that defeats the whole point

Also avoid Optional in performance-critical inner loops (each one is an extra object), and don't use it as a general replacement for every null check inside a method — a simple if is often clearer locally. The value of Optional is in APIs, where it communicates "this might be missing" to every caller.

Practical Example: Layered Configuration Lookup

Applications read settings from several places in order of priority — environment variables override a configuration file, which overrides built-in defaults. Each source may or may not contain a key, and blank values should count as "not set". Optional expresses "try this source, otherwise the next" directly.

import java.time.Duration;
import java.util.*;
import java.util.stream.*;

public class Cfg {
    record Source(String name, Map<String, String> values) {
        Optional<String> get(String key) {
            return Optional.ofNullable(values.get(key)).map(String::strip).filter(v -> !v.isEmpty());
        }
    }

    private final List<Source> sources;
    Cfg(Source... sources) { this.sources = List.of(sources); }

    Optional<String> lookup(String key) {
        return sources.stream().map(s -> s.get(key)).flatMap(Optional::stream).findFirst();
    }

    Optional<String> lookupWithOr(String key) {
        Source env = sources.get(0), file = sources.get(1), defaults = sources.get(2);
        return env.get(key).or(() -> file.get(key)).or(() -> defaults.get(key));
    }

    int intValue(String key) {
        return lookup(key).map(Integer::parseInt)
            .orElseThrow(() -> new IllegalStateException("missing required setting: " + key));
    }

    public static void main(String[] args) {
        Cfg cfg = new Cfg(
            new Source("env", Map.of("PORT", "9090", "DB_URL", "  ")),
            new Source("file", Map.of("DB_URL", "jdbc:postgresql://db/shop", "TIMEOUT", "PT45S")),
            new Source("defaults", Map.of("PORT", "8080", "TIMEOUT", "PT30S", "MAX_USERS", "100")));

        System.out.println("PORT      = " + cfg.intValue("PORT"));
        System.out.println("DB_URL    = " + cfg.lookup("DB_URL").orElse("-"));
        System.out.println("TIMEOUT   = " + cfg.lookup("TIMEOUT").map(Duration::parse).map(Duration::toSeconds).orElse(0L) + "s");
        System.out.println("MAX_USERS = " + cfg.lookupWithOr("MAX_USERS").orElse("-"));
        System.out.println("CACHE     = " + cfg.lookup("CACHE").orElse("(not set)"));
        try {
            cfg.intValue("SMTP_PORT");
        } catch (IllegalStateException e) {
            System.out.println(e.getMessage());
        }
        OptionalInt firstEven = IntStream.of(3, 5, 8, 10).filter(n -> n % 2 == 0).findFirst();
        System.out.println(firstEven + " " + firstEven.getAsInt());
    }
}

Output:

PORT      = 9090
DB_URL    = jdbc:postgresql://db/shop
TIMEOUT   = 45s
MAX_USERS = 100
CACHE     = (not set)
missing required setting: SMTP_PORT
OptionalInt[8] 8

How it works:

  1. Source.get turns a raw map value into an Optional: ofNullable handles missing keys, map(String::strip) trims whitespace, and filter treats an empty result as absent. That's why the blank DB_URL in the environment doesn't override the file's value.
  2. lookup streams the sources in priority order, maps each to its Optional value, keeps only present values with flatMap(Optional::stream), and takes the first. The stream is lazy, so lower-priority sources aren't consulted once a value is found.
  3. lookupWithOr expresses the same fallback chain with Optional.or (Java 9+): each supplier runs only if everything before it was empty. It's convenient when there's a small, fixed number of sources.
  4. Typed access: intValue converts with map(Integer::parseInt) and throws a clear exception for required settings that are missing, instead of failing later with a NullPointerException. TIMEOUT is converted from an ISO-8601 duration with two map steps.
  5. Optional settings use orElse to describe the absence (CACHE); required ones use orElseThrow (SMTP_PORT).
  6. OptionalInt appears naturally as the result of findFirst() on an IntStream.

Frameworks such as Spring Boot and MicroProfile Config resolve properties from layered sources by priority in the same way; MicroProfile Config, for example, offers getOptionalValue(name, type) for settings that may not be set.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Optional Class and get answers drawn from it.

Signed-in readers only.