Null check of Object and Object Chain in Java

null check in java

JDK 7 and earlier:
  1. Avoid using null check in if statement.
  2. Use ternary operator for null/exist check and assign a default value before using.
  3. This will make the code clear and more understandable as comparable to using multiple if, else  statements.
JDK 8 and above :
  1. Java-8 provides improved API to deal with object null check.
  2. 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());

  1. 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

Popular posts from this blog

Scala

Functional Programming