Java Optional

Optional was introduced in Java 8 and its primary objective is to prevent NullPointer exceptions in code.

Consider it as wrapper/container object which may or may not hold a non-null value. One needs to unwrap/de-containerize it to get the actual content using methods provided by Optional itself. For example – method ‘isPresent‘ invoked on Optional instance returns true if it contains a non-null value and method ‘get’ will return the actual content.

Let us try to understand this with below example.

In class ‘UsePersonClass’ we use a zero-argument constructor to create instance of ‘Person’ class (line 17). Thus, member variable of the instance will hold null.

So ‘person.getName()’ on line 20, will return Null. And since we have called ‘toLowerCase’ method on Null object, it throws NullPointer exception.

If we analyse, the reason for this exception are-

  1. In ‘Person’ class we declared return type of ‘getName’ function as String. This does not mandate the consumer of this class (in this example, UsePersonClass is its consumer) to do a check for Null values.
  2. The consumer class, ‘UsePersonClass’ missed to put explicit condition to check value returned by ‘getName()’ before invoking further methods on it.

As is evident, putting a null check condition in above program, should have prevented any exception situation. But in large programs where there are multiple provider/model classes (like the ‘Person’ class in this example) the consumer class (like UsePersonClass’ class in this example), one will require to put null checks at multiple steps, which would make the program bulky and difficult to read.

Now let’s see how Optional helps in improving this situation by modifying the earlier provider and consumer classes.

Highlights of this approach

  1. We have changed the return type of function ‘getName’ in ‘Person’ class, to return ‘Optional’ type rather than ‘String’ type (line 4)
  2. ‘Optional.ofNullable(name) converts the String value to an ‘Optional’ object.
  3. Now ‘UsePersonClass’ class CANNOT directly call ‘toLowerCase’ method as it is not available in ‘Optional’ type. Optional here forces user to first check if a non-null value is returned and only then perform further actions.
  4. There are other methods provided by Optional to verify, extract and process Optional object, in functional programming fashion.

Hence using Optional in Person class, we are hinting its consumer that it may or may not return a null value so the consumer can program accordingly and avoid Null Pointer exception.

Other ways to create instance of Optional

1. Optional<Object> personWrappedIntoOptional = Optional.of(person);

Use this only when you are sure that ‘person’ will not be Null. If there is possibility of ‘person’ to be Null, use Optional.ofNullable

2. Optional<Object> emptyOptional = Optional.empty();

Creates an empty Optional instance.

Illustration of usage of few methods provided by Optional:

79 thoughts on “Java Optional”

  1. I?m impressed, I must say. Really hardly ever do I encounter a blog that?s each educative and entertaining, and let me inform you, you could have hit the nail on the head. Your idea is excellent; the problem is one thing that not sufficient individuals are talking intelligently about. I’m very glad that I stumbled across this in my search for something regarding this.

  2. Magnificent beat ! I would like to apprentice at the same time as you amend your web site, how can i subscribe for a blog site? The account aided me a applicable deal. I had been a little bit acquainted of this your broadcast provided vibrant transparent idea

  3. คลิปโป๊ หี ควย เย็ด

    It is the best time to make a few plans for the longer term and it is time to be happy. I have learn this put up and if I may just I wish to recommend you some interesting things or advice. Perhaps you could write subsequent articles referring to this article. I wish to read more issues approximately it!

  4. I have observed that in the world nowadays, video games are classified as the latest popularity with kids of all ages. Often times it may be impossible to drag young kids away from the activities. If you want the very best of both worlds, there are plenty of educational activities for kids. Good post.

  5. ตำรวจ

    F*ckin? remarkable things here. I?m very satisfied to peer your article. Thank you so much and i’m taking a look ahead to touch you. Will you kindly drop me a mail?

  6. With havin so much written content do you ever run into any issues of plagorism or copyright violation? My site has a lot of completely unique content I’ve either created myself or outsourced but it looks like a lot of it is popping it up all over the web without my permission. Do you know any ways to help stop content from being stolen? I’d definitely appreciate it.

  7. Simply want to say your article is as astonishing. The clarity in your post is just excellent and i could assume you are an expert on this subject. Fine with your permission allow me to grab your feed to keep updated with forthcoming post. Thanks a million and please keep up the enjoyable work.

  8. Thank you for posting this. I really enjoyed reading it, especially because it addressed my question. It helped me a lot and I hope it will help others too.

  9. Concurseiros Unidos

    Wow! This can be one particular of the most useful blogs We’ve ever arrive across on this subject. Basically Wonderful. I am also a specialist in this topic so I can understand your effort.

  10. I really enjoyed reading your post, especially because it addressed my issue. It helped me a lot and I hope it can help others too.

  11. Thanks for posting. I really enjoyed reading it, especially because it addressed my issue. It helped me a lot and I hope it will help others too.

  12. Thank you for posting this. I really enjoyed reading it, especially because it addressed my question. It helped me a lot and I hope it will help others too.

  13. I really enjoyed reading your post, especially because it addressed my issue. It helped me a lot and I hope it can help others too.

  14. Heya i am for the first time here. I came across this board and I find It truly useful & it helped me out much. I hope to give something back and aid others like you helped me.

  15. I have been exploring for a bit for any high quality articles or blog posts on this kind of house .
    Exploring in Yahoo I finally stumbled upon this website. Studying this
    information So i am happy to express that I have an incredibly
    good uncanny feeling I came upon just what I needed.
    I such a lot without a doubt will make certain to don?t
    overlook this site and provides it a look regularly.

  16. I seriously love your blog.. Very nice colors & theme. Did you create this website yourself?
    Please reply back as I’m trying to create my very own blog and would love to know where you got this
    from or just what the theme is named. Thank you!

  17. Hey there just wanted to give you a quick heads up.
    The text in your content seem to be running off
    the screen in Ie. I’m not sure if this is a format issue or something to do
    with internet browser compatibility but I thought I’d post to let you know.
    The design look great though! Hope you get the problem fixed
    soon. Many thanks

  18. Link exchange is nothing else but it is just placing the other person’s blog link on your page at suitable place and other person will also do same in favor of you.

  19. Hey I know this is off topic but I was wondering if you knew of any
    widgets I could add to my blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this for quite some time and was hoping maybe
    you would have some experience with something like this.

    Please let me know if you run into anything.
    I truly enjoy reading your blog and I look forward to your
    new updates.

  20. This is the perfect website for anybody who really wants to find out about this topic.
    You know a whole lot its almost hard to argue with you
    (not that I actually would want to…HaHa). You certainly put a brand
    new spin on a subject that has been discussed for decades.
    Wonderful stuff, just excellent!

  21. An interesting discussion is definitely worth comment.
    I do believe that you ought to write more about this subject matter, it may not be
    a taboo matter but usually folks don’t talk about such issues.
    To the next! Cheers!!

  22. I go to see everyday a few blogs and blogs to read content, but this weblog
    presents quality based posts.

  23. Everything is very open with a clear clarification of the issues.
    It was really informative. Your website is useful.
    Thanks for sharing!

  24. An interesting discussion is definitely worth comment.

    I believe that you should publish more on this topic,
    it may not be a taboo matter but typically people don’t speak about such topics.
    To the next! Cheers!!

Leave a Comment

Your email address will not be published. Required fields are marked *