Null check of Object and Object Chain in Java
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.
- 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.setName("Pramoda");
employee.getDepartment();
// Getting optional value
Optional<Employee> optionalEmployee = Optional.ofNullable(employee);
//Set default value if the input object is null.
Employee
employee
= Optional.ofNullable(employee)
.map(Employee::getEmployee).orElse(new
Employee());
//Set default value if the input string is null
String
name
= Optional.ofNullable(employee)
.map(Employee::getName).orElse("Set
default value");
System.out.println("Is employee present :"+optionalemployee.isPresent());
System.out.println("Employee
object : "+employee);
System.out.println("Employee
Name : "+name);
Comments
Post a Comment