Some ways to initialize Optional object in Java

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:

  • 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.

If you pass a nullable reference variable, then the NPE error is normal.

Some ways to initialize Optional object in Java

  • 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:

If it is null then our Optional object is empty.


2.1/5 - (6 votes)

Add Comment