Table of Contents
- Reasons for NullPointerException
- 1. Invoking the instance method of a null object
- 2. Accessing or modifying the field of a null object.
- 3. Taking the length of null as if it were an array.
- 4. Accessing or modifying the slots of null as if it were an array.
- 5. Throwing null as if it were a Throwable value.
- 6. When you add null to Collections which do not allow nulls such as ConcurrentHashMap
- 7. Trying to synchronize using null object.
- Detection of NullPointerException
- Fix NullPointerException
- Best practices for avoiding NullPointerException
In this tutorial, we will see the most frequent java exception i.e. Exception in thread main java.lang.NullPointerException
. It is one of the Runtime Exception.
Raise your hand if you ever got NullPointerException while working on java code. I am sure that this is the exception you might have encountered most frequently. You might also agree that NullPointerException is pain for most of java developers(novice or expert), but there is not much we can do about them, because this is the price we need to pay for convenient or unavoidable null references.
Reasons for NullPointerException
Reasons for NullPointerException as defined by Java docs.
- Invoking the instance method of a null object.
- Accessing or modifying the field of a null object.
- Taking the length of null as if it were an array.
- Accessing or modifying the slots of null as if it were an array.
- Throwing null as if it were a Throwable value.
- When you add null to Collections which do not allow nulls such as [ConcurrentHashMap](https://java2blog.com/concurrenthashmap-in-java/ “ConcurrentHashMap”)
- Trying to synchronize using null object.
Let’s understand each of these in detail. I am creating a Employee class which we are going to use in our examples.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package org.arpit.java2blog; public class Employee { String name; int age; public Employee() { } public Employee(String name, int age) { this.name=name; this.age=age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } |
1. Invoking the instance method of a null object
This is most obvious one.
1 2 3 4 5 6 7 8 9 10 11 |
package org.arpit.java2blog; public class InvokingMethodOnNullMain { public static void main(String[] args) { Employee e1=null; String name = e1.getName(); System.out.println("Employee Name: "+ name); } } |
When you run above program, you will get below output.
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:7)
As you can see, e1 is null at line 7 and we are calling getMethod on it, thats why we are getting Exception in thread " main java.lang.NullPointerException
here.
2. Accessing or modifying the field of a null object.
It is very much similar to calling instance method on null.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package org.arpit.java2blog; public class NullFieldExampleMain { public static void main(String[] args) { Employee e1=null; String name = e1.name; System.out.println("Employee Name: "+ name); } } |
When you run above program, you will get below output.
at org.arpit.java2blog.NullFieldExampleMain.main(InvokingMethodOnNullMain.java:8)
As you can see, e1 is null at line 8 and we are accessing name field of e1, thats why we are getting NullPointerException here.
3. Taking the length of null as if it were an array.
When you try to get length of null array, you will get NullPointerException.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package org.arpit.java2blog; public class NullArrayLengthMain { public static void main(String[] args) { Employee[] arrEmp=null; int length = arrEmp.length; System.out.println("Length of array: "+length); } } |
When you run above program, you will get below output.
at org.arpit.java2blog.NullArrayLengthMain.main(InvokingMethodOnNullMain.java:9)
4. Accessing or modifying the slots of null as if it were an array.
When you try to access or modify null slot in array.Let’s understand with the help of example.
1 2 3 4 5 6 7 8 9 10 11 |
package org.arpit.java2blog; public class InvokingMethodOnNullMain { public static void main(String[] args) { Employee[] arrEmp=null; System.out.println(arrEmp[3]); } } |
When you run above program, you will get below output.
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:8)
5. Throwing null as if it were a Throwable value.
When you throw null as Throwable.
1 2 3 4 5 6 7 8 9 10 |
package org.arpit.java2blog; public class InvokingMethodOnNullMain { public static void main(String[] args) { throw null; } } |
When you run above program, you will get below output.
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:7)
6. When you add null to Collections which do not allow nulls such as ConcurrentHashMap
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package org.arpit.java2blog; import java.util.concurrent.ConcurrentHashMap; public class InvokingMethodOnNullMain { public static void main(String[] args) { ConcurrentHashMap<String, String> map=new ConcurrentHashMap<>(); map.put(null, "Dummy"); } } |
When you run above program, you will get below output.
at java.base/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1022)
at java.base/java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1017)
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:10)
7. Trying to synchronize using null object.
When you synchronize on null object, you will get NullPointerException
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package org.arpit.java2blog; import java.util.concurrent.ConcurrentHashMap; public class InvokingMethodOnNullMain { public static void main(String[] args) { Object obj=null; synchronized (obj) { ConcurrentHashMap<String, String> map=new ConcurrentHashMap<>(); map.put("Dummy", "value"); } } } |
When you run above program, you will get below output.
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:10)
Detection of NullPointerException
It is easier to detect NullPointerException. Check exception trace, it will tell you class name, method name and line number.Go to that line number and check what can be the reason for NullPointerException.
Fix NullPointerException
Let’s take above scenrios and fix NullPointerException.
1. Null check
check null before calling method or field.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; public class InvokingMethodOnNullMain { public static void main(String[] args) { Employee e1=null; if(e1!=null) { String name = e1.getName(); System.out.println("Employee Name: "+ name); } } } |
When you run above program, you won’t get NullPointerExcpetion.
2. Do null check as well before putting key or value in Collection which do not allow null
Best practices for avoiding NullPointerException
1. String comparison
This is most frequent reason for Exception in thread main java.lang.NullPointerException
, let’s understand with the help of example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package org.arpit.java2blog; public class StringComparisonMain { public static void main(String[] args) { Employee e1=new Employee(); if(e1.getName().equalsIgnoreCase("John")) { System.out.println("Employee Name is John"); } } } |
As we did not set name of Employee e1, we will get NullPointerException here.
When you run above program, you will get below output.
at org.arpit.java2blog.StringComparisonMain.main(StringComparisonMain.java:8)
You can change logic as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package org.arpit.java2blog; public class StringComparisonMain { public static void main(String[] args) { Employee e1=new Employee(); if("John".equalsIgnoreCase(e1.getName())) { System.out.println("Employee Name is John"); } } } |
This will avoid Exception in thread main java.lang.NullPointerException
.
Please note that it may cause unexpected behavior due to null. If name cannot be null at all for Employee, then don’t use above method as it will ignore null names in this case.
2. Use Optional
Java 8 has introduced a new class called Optional.In general, we do not find any value in method, we return null from it and it becomes pain for caller to check for null to use it.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public static Employee findEmployee(List<Employee employeeList,String name) { for(Employee e:employeeList) { if(e.getName().equalsIgnoreCase(name)) { return e; } } return null; } |
As you can see, if we did not find employee
in employeeList
, we are returning null from findEmployee()
method. The caller will get employee object from findEmployee()
method and may call getName() method which will in turn raise NullPointerException.You can use Optional to avoid such situations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
package org.arpit.java2blog; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class JavaOptionalMain { public static void main(String[] args) { List<Employee> employeeList = createEmployeeList(); Optional<Employee> employeeOpt = findEmployee(employeeList,"John"); if(employeeOpt.isPresent()) { Employee employee = employeeOpt.get(); System.out.println("Employee name: "+employee.getName()); } else { System.out.println("There is no employee with name John"); } } public static Optional<Employee> findEmployee(List<Employee> employeeList,String name) { for(Employee e:employeeList) { if(e.getName().equalsIgnoreCase(name)) { return Optional.of(e); } } return Optional.empty(); } public static List<Employee> createEmployeeList() { List<Employee> employeeList=new ArrayList<>(); Employee e1=new Employee("Adam",23); Employee e2=new Employee("Dave",34); Employee e3=new Employee("Carl",45); Employee e4=new Employee("Mohan",29); Employee e5=new Employee("Paresh",30); employeeList.add(e1); employeeList.add(e2); employeeList.add(e3); employeeList.add(e4); employeeList.add(e5); return employeeList; } } |
It gives indication to caller than returned value can be null.
3. Use ternary opertor
You can use ternary operation to check for null.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package org.arpit.java2blog; public class InvokingMethodOnNullMain { public static void main(String[] args) { Employee e1=null; String name = e1==null?e1.getName():""; System.out.println("Employee Name: "+ name); } } |
As you can see, we won’t get NullPointerException here.
4. Keep check on arguments of method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package org.arpit.java2blog; public class InvokingMethodOnNullMain { public static void main(String[] args) { String str=null; int len=getLength(str); System.out.println("Length of String:"+ len); } public static int getLength(String str) { if(str!=null) { return str.length(); } else { return 0; } } } |
5. Use StringUtils from Apache Common
You can use StringUtils
class to take care of lots of String null and empty String check. Sometimes you need to check if String is null or empty, you can use isEmpty method from StringUtils
to take care of it.
That’s all about Exception in thread "main" java.lang.NullPointerException in java.