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
Syntax
Optional.ofNullable(value)
Parameters
| Parameter | Description |
|---|---|
valueT |
A value or null. |
Return value
An Optional<T>.
Examples
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.
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
| Version | Change |
|---|---|
| Java Java 8 | Added |
Related
optional.orElse()· Return the value if present, otherwise a default. orElseGet() computes the default lazily, only when needed.optional.map()· Transform the value inside an Optional if present; an empty Optional stays empty. Chains safely without null checks.- Java Optional · tutorial