Java 25 (LTS) reference · Optional

Java Optional.ofNullable() Method

Wrap a value that might be null in an Optional, making 'no value' explicit. Optional.of() rejects null.

Java 25 (LTS) Since Java 8

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

Optional.ofNullable(value)

Parameters

ParameterDescription
value
T
A value or null.

Return value

An Optional<T>.

Examples

Present and empty
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Optional<String> name = Optional.ofNullable(null);
        Optional<String> other = Optional.of("Ana");
        System.out.println(name.isPresent() + " " + other.isPresent());
        System.out.println(name + " " + other);
    }
}

Output

false true
Optional.empty Optional[Ana]

Run this on your computer — see “Get Started” for setup.

Wrap a nullable lookup
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, String> emails = Map.of("ana", "[email protected]");
        Optional<String> email = Optional.ofNullable(emails.get("ben"));
        System.out.println(email.orElse("no email on file"));
    }
}

Output

no email on file

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 8Added

Was this page helpful?