The ofNullable() method of the Optional class creates an Optional object containing the specified value. When the value is null, it returns an empty Optional instead of throwing an exception.
- ofNullable() accepts both null and non-null values.
- A non-null value is stored inside the Optional object.
- A null value produces Optional.empty().
Example
Input: value = 9455
Output: Optional[9455]Input: value = null
Output: Optional.empty
Syntax:
public static <T> Optional<T> ofNullable(T value)
The method returns an Optional containing the specified value. For a null value, it returns an empty Optional.
1: Using ofNullable() with a Non-Null Value
The following program passes an integer value to ofNullable(). The value is stored inside the Optional object.
import java.util.*;
public class GFG {
public static void main(String[] args) {
Optional<Integer> op1 =
Optional.ofNullable(9455);
System.out.println("Optional 1: " + op1);
}
}
Output
Optional 1: Optional[9455]
Explanation: The value 9455 is not null, so ofNullable() creates an Optional containing that value. Printing the object displays Optional[9455].
2: Using ofNullable() with a Null Value
The following program passes null to ofNullable().
import java.util.*;
public class GFG {
public static void main(String[] args) {
Optional<String> op2 =
Optional.ofNullable(null);
System.out.println("Optional 2: " + op2);
}
}
Output
Optional 2: Optional.empty
Explanation: Since the specified value is null, ofNullable() returns an empty Optional. The empty instance is displayed as Optional.empty.