In Java, the Optional
object is a container object which may or may not contain a value. The Optional
class is present in the java.util
package.
Note: You can read more about the
Optional
class here.
ofNullable()
method of the Optional
class?The ofNullable()
method is used to get an instance of the Optional
class with a specified value.
If the value is null
, then an empty Optional
object is returned.
public static <T> Optional<T> ofNullable(T value)
This method takes a value that will be present in the Optional
object.
This method returns an Optional
object with the specified value. If the argument value is null
, then an empty Optional
object is returned.
The below code shows how to use the ofNullable()
method:
import java.util.Optional;class OptionalOfNullableExample {public static void main(String[] args) {Optional<Integer> optional1 = Optional.ofNullable(1);System.out.println("Optional1: " + optional1);Optional<String> optional2 = Optional.ofNullable(null);System.out.println("\n\nOptional2: " + optional2);System.out.println("Optional2.isPresent: " + optional2.isPresent());}}
In the above code:
Optional
class.import java.util.Optional;
ofNullable()
method to get an Optional
object of the Integer
type with value 1
.Optional<Integer> optional1 = Optional.ofNullable(1);
optional1;// Optional[1]
ofNullable()
method with null
as an argument. This method returns an empty Optional
object because we send null
as the value for the Optional
object.Optional<String> optional2 = Optional.ofNullable(null);
optional2;// Optional.empty
optional2.isPresent(); // false