21 April, 2018

Check NullPointerException in jdk 8 - Use Optional



How to handle NullPointerException or null check in jdk 8 ? Checking null in jdk 8 using Optional<T>.

NullPointerException is most common exception which each developer need to handle. Its very common while you are playing around many object. Before JDK 8 , it was a tedious task and lots of boilerplate code you need to write to handle this NullPointerException. But, after JDK 8 it Make your code more readable and protect it against null pointer exceptions. This API will help to write cleaner and more readable code , with intelligence to handle null check internally.

Below Example has few demonstration , how to use the Optional<T> api to avoid NullPointerException. You can handle Null check for your object.


Employee.java


package com.javadevelopersguide.tutorial.jdk8;
/**
 * Employee Object
 *
 * @author manoj.bardhan
 *
 */
public class Employee {
private String empName;
private int age;
private Address empAddress;
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Address getEmpAddress() {
return empAddress;
}
public void setEmpAddress(Address empAddress) {
this.empAddress = empAddress;
}
}



Address.java

package com.javadevelopersguide.tutorial.jdk8;
/**
 * Address Object
 *
 * @author manoj.bardhan
 *
 */
public class Address {
private String homeUnitNo;
private String streetNo;
private String city;
public String getHomeUnitNo() {
return homeUnitNo;
}
public void setHomeUnitNo(String homeUnitNo) {
this.homeUnitNo = homeUnitNo;
}
public String getStreetNo() {
return streetNo;
}
public void setStreetNo(String streetNo) {
this.streetNo = streetNo;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}



NullPointerCheck.java


package com.javadevelopersguide.tutorial.jdk8;
import java.util.Optional;
/**
 * This Example demonstrate how to use JDK 8 Optional<T> Api
 *
 * @author manoj.bardhan
 *
 */
public class NullPointerCheck {
public static void main(String[] args) {
String empName = null;
/**
* Before jdk 8, This will print "Print null"
*/
if (null != empName) {
System.out.println("Print not null");
} else {
System.out.println("Print null");
}
/**
* Before jdk 8, throws NullPointerException
*/
try {
if (empName.equals("SomeThing")) {
System.out.println("Print SomeThing");
}
} catch (Exception e) {
e.printStackTrace();
}
/**
* So Now , jdk 8 provides easy and clean API i.e Optional<T> for
* handling this type of scenario.
*/
Optional<String> optionalString = Optional.ofNullable(empName);
if (optionalString.isPresent()) {
System.out.println("Employee Name ::" + empName);
}
/**
* How to work with your own objects.
*/
Employee employee = new Employee();
employee.setEmpName("Peter");
Optional<Employee> optionalEmployee = Optional.ofNullable(employee);
if (optionalEmployee.map(Employee::getEmpAddress).isPresent()) {
System.out.println(employee.getEmpName() + "-  Address is registered");
} else {
System.out.println(employee.getEmpName() + "-  Address is  null");
}
Employee employee1 = new Employee();
employee1.setEmpName("Mark Garret");
Address address = new Address();
address.setCity("Sydney");
employee1.setEmpAddress(address);
Optional<Employee> optionalEmployeeWithAddress = Optional.ofNullable(employee1);
if (optionalEmployeeWithAddress.map(Employee::getEmpAddress).isPresent()) {
System.out.println(employee1.getEmpName() + "-  Address is " + address.getCity());
} else {
System.out.println(employee1.getEmpName() + "-  Address is  null");
}
/**
* Use Optional.empty() for set the default value for an object.
*/
Employee empObject = new Employee();
System.out.println("Returns Optional empty Value ::" + Optional.empty());
/*
* Optional.of() method doesn't handle NullPointer, be careful of this
* method while using.Always use the ofNullable() before null check.
*/
System.out.println(
"Returns Optional empty Value ::" + Optional.of(empObject).map(Employee::getEmpAddress).isPresent());
}
}

Output:-

Print null
java.lang.NullPointerException
at com.javadevelopersguide.tutorial.jdk8.NullPointerCheck.main(NullPointerCheck.java:48)
Peter-  Address is  null
Mark Garret-  Address is Sydney
Returns Optional empty Value ::Optional.empty
Returns Optional empty Value ::false



I have used below methods from Optional<T> :-

empty() - Returns an empty Optional instance


of() - Returns an Optional with the specified present non-null value.


isPresent() - If a value is present, invoke the specified consumer with the value, otherwise do nothing.


map() - If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result.


ofNullable() - Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.


There are few more methods are there, you can give a try. Below link will give you a complete information. Read more about the Optional<T> by JDK 8.



Hope it will help you.