DEV Community

Java 8 Optional: A way to avoid NullPointerException

arpitmandliya on April 11, 2019

In this post, we will see about Java 8 optional. Did you ever get NullPointerException as Java developer? If you are experienced Java developer, y...
Collapse
 
cubiclebuddha profile image
Cubicle Buddha

Yes, optional is a great pattern. Have you tried Kotlin, Swift, or TypeScript which have the choice of non-nullable references? It’s a much more effective way of eliminating null references. That being said, I still use Optional or Either pattern in TypeScript when I want to return one of two types. I’m glad to find another fan of this defensive programming technique. :)

Collapse
 
verdoso profile image
Daniel Lopez

It is worth mentioning that Optional has seen some improvements in versions after Java 8 and it is now much more interesting to use.
The new methods ifPresentOrElse(), or(), orElseThrow(), isEmpty(), map(), flatMap()...

Now we are talking! :D
Cheers!

Collapse
 
manhdat107 profile image
Vu Manh Dat • Edited

great article, but I have a little confused about this. when you check optional is present, in this case, I can check this is null or not ... why don't do that? cuz looks quite the same.

Collapse
 
pahangkrisdyan profile image
Pahang Krisdyan

Optional force us to check the presence to avoid human error.

Collapse
 
pam_stums profile image
Pam Stums

Good question and excellent answer! Thank you!

Collapse
 
williams-37 profile image
Williams

using of( ) will throw exception?

Collapse
 
verdoso profile image
Daniel Lopez

Yes, Optional.of will throw an Exception if you pass a null value. If you cannot be sure that the value will not be null, then use Optional.ofNullable(..,);

One just has to wonder why they did not make it the default behaviour with the short name.
¯_(ツ)_/¯

Collapse
 
erfannvb profile image
Erfan

I think one of the best features introduced in Java 8 was Optional. However, in my opinion, it can sometimes be a little confusing.

Collapse
 
pam_stums profile image
Pam Stums

Yes I feel the same. It’s like you need to know when to use it. What are the cases it’s good for. You might want to explore using it with map() it’s a powerful tool.

Collapse
 
praveen_nareshit_323 profile image
Praveen Nareshit

Excellent Blog very imperative good content
Core Java Training in KPHB

Collapse
 
iammtander profile image
Mitchell Mutandah

Thanks for sharing!