The Optional Class in Java


Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value.

Source Code

Optional optional = Optional.of("hello");
if (optional.isPresent()) {  // Check for value is present or not
    System.out.println(optional.get());  // prints hello
}

Use Optional to more gracefully handle the possibility of null values in your applications, avoiding NullPointerException.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments