What is the Optional.of() method in Java?
In Java, an 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
Optionalclass here.
What is the of() method of the Optional class?
The of() method is used to get an instance of the Optional class with the specified not-null value.
public static <T> Optional<T> of(T value)
Argument
value: This is the value which is to be present in theOptionalobject.valueshould not benull.
Return value
This method returns an Optional object with the specified value.
Code
The below code shows how to use the of() method:
import java.util.Optional;class OptionalOfExample {public static void main(String[] args) {Optional<Integer> optional1 = Optional.of(1);System.out.println("Optional1 : " + optional1);Optional<String> optional2 = Optional.of("test");System.out.println("Optional2 : " + optional2);}}
Explanation
In the above code:
- In line 1, we import the
Optionalclass.
import java.util.Optional;
- In line 5, we use the
of()method to get anOptionalobject of theIntegertype with value1.
Optional<Integer> optional1 = Optional.of(1);
optional1;// Optional[1]
- In line 8, we use the
of()method to get anOptionalobject of theStringtype with valuetest.
Optional<String> optional2 = Optional.of("test");
optional2;// Optional[test]