I have a question regarding Java 8\'s Optional, the purpose of which is to tackle NullPointerException
exceptions.
The question is, what is the reason for h
the purpose of Optional is to tackle
NullPointerException
exception
Yes, it is, but at usage time not at creation.
So when you receive an Optional
from a method then you can avoid NPE by using Optional.ifPresent
, Optional.orElse
,Optional.orElseGet
and Optional.orElseThrow
methods.
But this is not the case when you're creating an Optional. Since it's your own method you have to know whether the object is nullable or not.
The main point of Optional is to provide a means for a function returning a value to indicate the absence of a return value. See this discussion. This allows the caller to continue a chain of fluent method calls.
Stuart Marks
Please read this post for more detailed explanation.