[Solved] NullPointerException In Java


NullPointerException is Runtime Exception and Unchecked Exception which thrown when trying to access an object which is having value as null.

What is Null Value?

Null value is a special  value which tell JVM this reference variable is assigned with no value as null. It means variable is not pointing to any object instances and not having any value.

Cases when NullPointerException Happen:

  • Accessing or modifying a null object’s field.
  • Taking length of null  from object like String, Array, ArrayList etc.
  • Invoking a method from a null object.
  • Calling method passing argument as wrapper object having null value while method having primitive arguments.
  • Accessing or modifying the slots of null object, as if it were an array.
  • Throwing null, as if it were a Throwable value.
  • When you try to synchronize over a null object.

Below are some examples for NullPointerException for above cases which showing how NullPointerException can happen in your code.

import java.util.List;

public class NullPointerExceptionExample {

	public static void main(String[] args) {
		//Example 1: String object assigned with null
		try
		{
		String str=null;
		if(str.length()>0)//NullPointerException Here
			System.out.println("String Length :"+str.length());
		}
		catch(NullPointerException ex)
		{
			System.out.println("Example 1 :String object assigned with null");
			ex.printStackTrace();
		}

		//Example 2: Collection List Object Assigned with Null
		try
		{
		List list=null;
		if(list.size()>0)//NullPointerException Here
			System.out.println("List Length :"+list.size());
		}
		catch(NullPointerException ex)
		{
			System.out.println("Example2 :Collection List object assigned with null");
			ex.printStackTrace();
		}

		//Example 3: Calling method with wrapper and method having primitive value
		try
		{
		Long acNumber=null;
		checkValue(acNumber);
		}
		catch(NullPointerException ex)
		{
			System.out.println("Example 3 :Calling method with wrapper and method having primitive type");
			ex.printStackTrace();
		}

		//Example 4 :Accessing slot of Array object having value as null
		try
		{
		Employee [] empArr=new Employee[10];
		System.out.println("Employee Name :"+empArr[5].getName());
		}
		catch(NullPointerException ex)
		{
			System.out.println("Example 4: Accessing slot of array objet having value as null");
			ex.printStackTrace();
		}
	}

	public static void checkValue(long acNumber)
	{
		System.out.println("Account Number:"+acNumber);
	}

	private class Employee
	{
		private int id;
		private String name;
		private double salary;

		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public double getSalary() {
			return salary;
		}
		public void setSalary(double salary) {
			this.salary = salary;
		}

	}

}

Output :

Example 1 :String object assigned with null
java.lang.NullPointerException
	at example.NullPointerExceptionExample.main(NullPointerExceptionExample.java:12)
Example2 :Collection List object assigned with null
java.lang.NullPointerException
	at example.NullPointerExceptionExample.main(NullPointerExceptionExample.java:25)
Example 3 :Calling method with wrapper and method having primitive type
java.lang.NullPointerException
        at
example.NullPointerExceptionExample.main(NullPointerExceptionExample.java:38)
Example 4: Accessing slot of array objet having value as null
java.lang.NullPointerException
	at example.NullPointerExceptionExample.main(NullPointerExceptionExample.java:50)

 How to avoid NullPointerException?

NullPointerException can be avoid by using considering below points:

  • Need to ensure object as initialize properly before any operation check for null .
  • Need to ensure object reference is not null before calling any method or operation on fields.
  • While comparing string with literals. Instead of invoking the method from the null object, consider invoking it from the literal.
  • Before calling method check arguments if valid then only call methods.
  • Use of Ternary operator for initialize with some default value if object value is null.
  • We can use NullPointerException catch block when no action perform or if need to throw some Customize Exception or User Defined Exception.

In below example consider all above case for avoid NullPointerException.

public class NullPointerExceptionExample {

	public static void main(String[] args) {
		//Example 1: String object assigned with null
		//NullPointerException avoided by checking null before use
		String str=null;
		if(str!=null && str.length()>0)
			System.out.println("String Length :"+str.length());

		//Example 2: Object assigned with Null
		//NullPointerException avoided by using  null check before accessing field
		Employee emp=null;
		if(emp!=null)
			System.out.println("Employee Name :"+emp.getName());

		//Example 3: name is assigned with null
		//NullPointerException avoided by calling equals method from literals instead of name object.
		String name=null;
		if("FacingIssuesOnIT".equals(name))
		{
			System.out.println("Name is FacingIssuesOnIT");
		}
		else
		{
			System.out.println("Name is not FacingIssuesOnIT");
		}

		//Example 4: Calling method with wrapper as null and method having primitive value
		//NullPointerException avoided by checking null on method arguments before calling method.

		Long acNumber=null;
		if(acNumber!=null)
		{
		checkValue(acNumber);
		}

		//Example 5: Object reference value is null and need to perform operation
		//NullPointerException avoided by using ternary operator
		String siteName=null;
		name=siteName==null?"":siteName;
		System.out.println("Site Name Length:"+name.length() );

	}

	public static void checkValue(long acNumber)
	{
		System.out.println("Account Number:"+acNumber);
	}

	private class Employee
	{
		private int id;
		private String name;
		private double salary;

		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public double getSalary() {
			return salary;
		}
		public void setSalary(double salary) {
			this.salary = salary;
		}

	}

}

Summary

  • Here you have learn about NullPointerException and Null value.
  • Cases with examples where NullPointerException can happen.
  • Al so explained with example to avoid NullPointerException by applying null check on object, compare String values by calling operations on literals and using ternary operators.

One thought on “[Solved] NullPointerException In Java”

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s