Java 8 Optional Example

In the post Java 8 Optional Example, you’re introduced how to use the new java.util.Optional class. It is a public final class and used to deal with NullPointerException in Java application.

What is the Type of Null?

There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type. For example, field members of objects are automatically initialized to null and programmers typically initialize reference types to null when they don’t have an initial value to give them and, in general, null is used everytime where we don’t know or we don’t have a value to give to a reference.

What is wrong with just returning null?

For the ones that do not know what a NullPointerException is, just try:

The code above would compile but you would get a warning like this:

In order to handle this problem, you can check and validate for null, or you can surround the block with a try catch. In Java 8, you can handle this issue using the new Optional class.

Java 8 Optionals

a) Creating Optional objects

In order to create an Optional we have to indicate what type of value is going to contain. There are 3 major ways to create an Optional, here.

*) Create empty optional using Optional.empty().

*) Using Optional.of() to create optional with default non-null value.

*) Using Optional.ofNullable() to create an Optional object that may hold a null value.

b) Java Optional Example: If Value is not Present

Ouput should be printed like this

c) Java Optional Example: If Value is Present

Ouput should be printed like this

d) Java Optional Methods Example: filter; hashCode; ofNullable; orElse methods

Ouput should be printed like this
Java 8 optional example

Using Optional that helps to reduce the number of null pointer exceptions and the overall number of bugs in Java application. The purpose of Optional is not to avoid all types of null pointers

That’s all for Java 8 Optional Example.


Download complete source code, click link below (217 downloads)

Leave a Comment


Please share it if you found this useful
Hide Buttons