In the previous tutorial, I introduced with you all about the Optional object in Java. In this tutorial, let’s find out some ways to initialize your Optional object in Java.
OK …
- First, we can initialize an Optional object with the nulled reference variable.
For example, if you want to initialize an Optional of String object with a nulled String, you would do the following:
1 |
Optional<String> opt = Optional.empty(); |
- The second is that we will initialize an Optional object with the specified reference variable to an object.
In this way, you must pass a reference variable to the object that already initialized.
1 2 |
String s = new String("Khanh"); Optional<String> opt = Optional.of(s); |
If you pass a nullable reference variable, then the NPE error is normal.
- The third way is that we can initialize an Optional object with a reference variable that can be null or not.
This is the most common way to create an Optional object. We do not care about the value of the reference variable:
1 2 |
String s = new String("Khanh"); Optional<String> opt = Optional.ofNullable(s); |
If it is null then our Optional object is empty.