Posts

Showing posts from July, 2018

Null check of Object and Object Chain in Java

Image
JDK 7 and earlier: Avoid using null check in if statement. Use ternary operator for null/exist check and assign a default value before using. This will make the code clear and more understandable as comparable to using multiple if, else   statements. JDK 8 and above : Java-8 provides improved API to deal with object null check. Use isPresent() function available in Java.util.Optional interface for null check of single object. Ex – Employee employee = new Employee(); employee .setName( "Pramoda" ); // Getting optional value Optional<Employee> optionalEmployee = Optional. ofNullable ( employee ) .map(Root::getEmployee); System. out .println( "Is Employee present : + optionalemployee .isPresent()); Use Java.util.Optional functional interface for object null check and assign default value to avoid null pointer exception. Ex – Employee employee = new Employee(); employee .setNa