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.

13 comments:

  1. You've made some good points there. I looked on the internet for additional information about the issue and found most people will go along with your views on this website.
    Best Java Training Institute Marathahalli
    Advanced Java Training Center In Bangalore

    ReplyDelete
  2. Thanks for Sharing This Article.It is very so much valuable content."Nice blog I really appreciate your words,Nice post. thanks lot!!

    Java training in Bangalore

    Java training in Hyderabad

    Java Training in Coimbatore

    Java Training

    Java Online Training

    ReplyDelete
  3. very nice blogs!!! i have to learning for lot of information for this sites...Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.

    Web Designing Training in Chennai

    Web Designing Course in Chennai

    Web Designing Training in Bangalore

    Web Designing Course in Bangalore

    Web Designing Training in Hyderabad

    Web Designing Course in Hyderabad

    Web Designing Training in Coimbatore

    Web Designing Training

    Web Designing Online Training

    ReplyDelete
  4. The post is absolutely fantastic! Lots of great information and inspiration both of which we all need! Also like to admire the time and effort you put into your blog.

    python training in bangalore

    python training in hyderabad

    python online training

    python training

    python flask training

    python flask online training

    python training in coimbatore


    ReplyDelete
  5. As of 2016, there are approximately 2 million software developers in India, with about 50,000 of those developing for mobile, and Google is trying to increase the figure for Android specifically.keep it up!!

    Android Training in Chennai

    Android Online Training in Chennai

    Android Training in Bangalore

    Android Training in Hyderabad

    Android Training in Coimbatore

    Android Training

    Android Online Training

    ReplyDelete
  6. Nice. I am really impressed with your writing talents and also with the layout on your weblog. Appreciate, Is this a paid subject matter or did you customize it yourself? Either way keep up the nice quality writing, it is rare to peer a nice weblog like this one nowadays. Thank you, check also event management and 3 Key Digital Learning Lessons From SXSW

    ReplyDelete
  7. wesome article! You are providing us very valid information. This is worth reading. Keep sharing more such articles. Get All JAVA Tutorials In one place , Thank you very much! ❤❤❤

    ReplyDelete
  8. CopyCat is a great Figma Plugin Development tool to quickly get started with development. It's simple to use and install, and it comes with a wide range of features that make developing for Figma much easier.

    ReplyDelete