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:

72 thoughts on “Java Optional”

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

  8. 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.

  9. 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.

  10. 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.

  11. 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!

  12. 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

  13. 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.

  14. 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.

  15. 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!

  16. 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!!

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

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

  19. 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 *