A quick guide to Optional ofNullable() method in Java 8 API with Example programs. How to use in the real time projects.
API Note: Returns an Optional describing the given value, if non-null, otherwise returns an empty Optional.
This method same as Optional.of() method and additionally supports null values. It does not throw NullPointerException if we pass null to it.
If we are not sure about the value then using ofNullable() method is suggestable.
Let us see the syntax and example programs.
2. Optional ofNullable Syntax
ofNullable syntax is below.
ofNullable() is a static method and can be accessed directly with the class name. ofNullable() returns Optional object.
This method accepts any type of value.
3. Java 8 ofNullable() Example
Let us write an example java program on ofNullable().
Assume that getValue() is a third party API method and we do not know the value returns. The returned value may be null or non-null. In such cases, We should use ofNullable() instead of of() method.
In the output, We are seeing the value for the indiaOptional as Delhi. But, seeing Optional.empty for usOptional. Because ofNullable method internally calls Optional.empty() method if the null value is passed to it.
Internal Implementation Code:
Let us take a look at the below example to check value is present using
If you use of() method, it will throw NullPointerException.
In this article, We’ve seen how to create an Optional object for any nullable or non-null value. This method also is a static method as empty() and of() methods of Optional class. This will not throw any runtime exception for any value.
An example scenario where to use ofNullable() method.
And also seen its internal implementation logic.