Optional DataType JDK 8

how do you normally do a NULL check inside the java application. if you’re using older jdk, just using the if to check whether the object is null or not, something like below …

 

if(myObject != null){
... // do something
}

by using new JDK 8, there is a wrapper class that could wrap object type and basically provides some features for developers and in simple words, do the heavy lifting internally, make the code compact and more readable.

 

please check below example.


Optional<MyDataType> returnedInstance = myObjInstance.getMeSomething();

 

Notes:
1. mechanism to check whether the return type contains the NULL pointer exception or not.
2.decrease the null pointer exception thrown by the application.
3. due to suggestion by openJDK mailing list — only use the Optional in return tye
3.a: still needed to check for input params for functions and methods inside the classes.
4. Checked exception can be used with Optional to handle and signal the entier application whenever the unexpected status would be met.
5. something like this …
Optional<TypeIAmExpecting> = getMySomething(String input);

ifPresent() — return true if value is not null and would be presented.
orElse(defultValue);
get(); — get the value
isPresent() — check in ifelse statement and ha get() or handle the no-exited stateus.

when to use: as return type

 

 

Advertisements