Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

java.lang.NullPointerException

In this tutorial, we will see the most frequent java exception i.e. 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
  • 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.

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.

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.

Exception in thread “main” java.lang.NullPointerException
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 NullPointerException here.

2. Accessing or modifying the field of a null object.

It is very much similar to calling instance method on null.

package org.arpit.java2blog;

public class InvokingMethodOnNullMain {

	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.

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.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.

package org.arpit.java2blog;

public class InvokingMethodOnNullMain {

	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.

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.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.

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.

Exception in thread “main” java.lang.NullPointerException
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.

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.

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:7)

6. When you add null to Collections which do not allow nulls such as ConcurrentHashMap

package org.arpit.java2blog;

import java.util.concurrent.ConcurrentHashMap;

public class InvokingMethodOnNullMain {

	public static void main(String[] args) {
		ConcurrentHashMap map=new ConcurrentHashMap();
		map.put(null, "Dummy");
	}
}

When you run above program, you will get below output.

Exception in thread “main” java.lang.NullPointerException
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

package org.arpit.java2blog;

import java.util.concurrent.ConcurrentHashMap;

public class InvokingMethodOnNullMain {

	public static void main(String[] args) {
		Object obj=null;
		synchronized (obj) {
			ConcurrentHashMap map=new ConcurrentHashMap();
			map.put("Dummy", "value");
		}
	}
}

When you run above program, you will get below output.

Exception in thread “main” java.lang.NullPointerException
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.

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 NullPointerExcpetion, let’s understand with the help of example.

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.

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.StringComparisonMain.main(StringComparisonMain.java:8)

You can change logic as below.

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 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:

public static Employee findEmployee(List

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.

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 employeeList = createEmployeeList();
		Optional 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 findEmployee(List employeeList,String name)
	{
		for(Employee e:employeeList)
		{
			if(e.getName().equalsIgnoreCase(name))
			{
				return Optional.of(e);
			}
		}
		return Optional.empty();
	}
	public static List createEmployeeList()
	{
		List 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;
	}
}
There is no employee with name John

It gives indication to caller than returned value can be null.

3. Use ternary opertor

You can use ternary operation to check for null.

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

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 NullPointerException in java.

The post java.lang.NullPointerException appeared first on Java2Blog.



This post first appeared on How To Learn Java Programming, please read the originial post: here

Share the post

java.lang.NullPointerException

×

Subscribe to How To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×