Java 8 introduces Optional to deal with NPE. In practical application,I can‘t understand a problem.
I have the method A
public void doSomethingA(String para) {
Optional<String> name = Optional.of(para);
if (name.isPresent()) {
//do
}
}
But if para = null, it will throw NPE.
method B
public void doSomethingB(String para) {
if (para != null) {
//do
}
}
if I check para is not null, What's the difference between A and B.
Where is the meaning of Optional.
With Optional , the . of() method notices the null value and throws the NullPointerException immediately - potentially also crashing the program.
Optional is primarily intended for use as a method return type where there is a clear need to represent "no result," and where using null is likely to cause errors. A variable whose type is Optional should never itself be null . It should always point to an Optional instance.
Optional is an API that was introduced in Java 8. If used right, it can solve the problem of the Null Pointer Exception. Optional API implements functional programming and uses Functional Interface.
In Java 8 you can return an Optional instead of a null . Java 8 documentation says that an Optional is "A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value."
Use Optional.ofNullable
if you are unsure whether you have a value or not, but you do not want a NullPointerException
to be thrown.
Use Optional.of
if you know you have a non-null-value or if it's ok for you if a NullPointerException
is thrown otherwise.
Regarding the rest of your question: why null
or Optional
you may find the following question useful: Optional vs. null. What is the purpose of Optional in Java 8?
Your question may also be related to: Why use Optional.of over Optional.ofNullable?
Optional does not prevent from throwing an NPE, It makes it very easy to avoid, but you have to do your part, for example, I would refactor your code to something like this.
public void doSomethingA(String para) {
Optional<String> optName = Optional.ofNullable(para);
String name = optName.orElse("Unknown");
//At his point, you are completely sure that name is even given name or "Unknown"
//and can do wherever you want without being afraid of throwing a NPE
}
You can use other optional Method like:
optName.orElseThrow()
to throw and error if your param is null, optName.orElseGet(() -> { return "Unknown" ;});
practically does the same than the example but you can add more logic to get the default value, or many other methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With