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());
}
}
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.
Follow for more details on @Facebook!!!
Find More :-
Find More :-
- Write your first groovy program.
- Top 10 groovy interview question.
- Difference between groovy and java.
- What is full stack development experience.
- 5 fundamental questions of groovy.
- Write your first java program.
- Reverse string using recursive method in java.
- Java 8 use Option - avoid NullPointerException
- Producer & Consumer problem solution using BlockingQueue.
- Comparator Interface with Examples
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.
ReplyDeleteBest Java Training Institute Marathahalli
Advanced Java Training Center In Bangalore
Thanks for Sharing This Article.It is very so much valuable content."Nice blog I really appreciate your words,Nice post. thanks lot!!
ReplyDeleteJava training in Bangalore
Java training in Hyderabad
Java Training in Coimbatore
Java Training
Java Online Training
Nice blog...
ReplyDeleteArtificial Intelligence Training in
Chennai
Ai Training in Chennai
Artificial Intelligence training in
Bangalore
Ai Training in Bangalore
Artificial Intelligence Training in
Hyderabad | Certification | ai training in hyderabad
Artificial Intelligence Online Training
Ai Online Training
Blue Prism Training in Chennai
Thank you for the information. It is very useful and inforrmative
ReplyDeleteangular js course in chennai
angular course in chennai
angular js online course in chennai
angular js course in bangalore
angular js course in hyderabad
angular js course in coimbatore
angular js course
angular js online course
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.
ReplyDeleteWeb 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
Thanks for Sharing This Article.It is very so much valuable content."Nice blog I really appreciate your words,Nice post. thanks lot!!
ReplyDeleteAWS Course in Chennai
AWS Course in Bangalore
AWS Course in Hyderabad
AWS Course in Coimbatore
AWS Course
AWS Certification Course
AWS Certification Training
AWS Online Training
AWS Training
Thanks for sharing this wonderful content.its very useful to us.This is incredible,I feel really happy to have seen your webpage I gained many unknown information.
ReplyDeleteacte chennai
acte complaints
acte reviews
acte trainer complaints
acte trainer reviews
acte velachery reviews complaints
acte tambaram reviews complaints
acte anna nagar reviews complaints
acte porur reviews complaints
acte omr reviews complaints
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.
ReplyDeletepython training in bangalore
python training in hyderabad
python online training
python training
python flask training
python flask online training
python training in coimbatore
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!!
ReplyDeleteAndroid 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
Amazing!! This content is really useful and I understood it properly...thank you so much for this article
ReplyDeleteCyber Security Training Course in Chennai | Certification | Cyber Security Online Training Course | Ethical Hacking Training Course in Chennai | Certification | Ethical Hacking Online Training Course | CCNA Training Course in Chennai | Certification | CCNA Online Training Course | RPA Robotic Process Automation Training Course in Chennai | Certification | RPA Training Course Chennai | SEO Training in Chennai | Certification | SEO Online Training Course
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
ReplyDeletewesome 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! ❤❤❤
ReplyDeleteCopyCat 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