Java NullPointerException – Reasons for Exception and How to Fix?

In this tutorial you will learn about Java NullPointerException and ways to fix this.

A runtime error that can be handled by the programmer is called an Exception. Some exceptions that are checked at compile time are called Checked Exceptions, these also called compile time errors. But the term we are using Exception only refers to Unchecked exceptions which are checked by JVM but not by compiler.

Java NullPointerException

Java.lang.NullPointerException is one of the most common exception in Java that programmers mostly face.

Note: Whenever I am referring Unchecked Exceptions, consider it as NullPointerException also. Because this is one type of Unchecked Exception.

Since everything in Java is a class, errors are also represented by the classes. So there is a class called NullPointerException in Java.

Hierarchy of NullPointerException Class in Java

Java NullPointerException

Throwable is class that represents all errors and exceptions in Java. That means Throwable contains two type of classes Error and Exception. All exceptions super class is “Exception”. NullPointerException is come under RuntimeException. So NullPointerException extends RuntimeException.

Possible Reasons for NullPointerException

There are mainly 4 reasons for the occurrence of NullPointerException in Java.

Case 1: With String

If a string is declared as null and we try to perform any actions on it even if we apply inbuilt functions on it. It will throw NullPointerException.

Example:

public class Fst{
	public static void main(String[] args){
		String str = null;
		System.out.println(str.toString());
		System.out.println(str.toUpperCase());
	}
}

Output

Exception in thread “main” java.lang.NullPointerException at Fst.main(Fst.java:4)

Case 2: With Objects

If any object reference is null we can’t perform any operations on it. First an object should be instantiated to use further in-order to avoid null pointer exception.

Example:

public class Second{
	public static void main(String[] args)
	{
			Object object=null;
			System.out.println(object.equals(object));
	}
}

Output

Exception in thread “main” java.lang.NullPointerException at Second.main(Second.java:4)

Case 3: With Collections and Data-members

If any value in the data is null and if we try to perform operations over it, then it will throw null pointer Exception

Example:

import java.util.ArrayList;

public class Third{
	public static void main(String[] args){	
		ArrayList<Object> arr=new ArrayList<Object>();
		arr.add(null);
		System.out.println(arr.get(0).hashCode());
	}
}

Output

Exception in thread “main” java.lang.NullPointerException at Third.main(Third.java:6)

Case 4: Referring other class Data-Members

If we create an object of another class and try to access the uninitialized data members of that class, then it will raise null pointer exception.

Example:

public class Four{
	public static void main(String[] args) {
		OtherClass other=new OtherClass();
		System.out.println(other.getStr().toCharArray());
	}
}
// The above code write in Four.java file
// This below code write in OtherClass.Java file
public class OtherClass {
	String str;

	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}
}

Now run Four.java file.

Ouput

Exception in thread “main” java.lang.NullPointerException at Four.main(Four.java:4)

Handling NullPointerException

One thing is sure that we shouldn’t avoid the using Null in Java. It says that no value is assigned to reference variable. It has various applications also. When we implementing data structures like linked lists we should use Null. Since we shouldn’t avoid, we should handle it. There are some methods to do this.

  • Try to stop the null at design level only. Don’t allow the possibility of null value in object.
  • Always declaring and initializing reference variables is best way before using them.
  • The mostly effected NullPointerException values are Arrays. So it’s better to initialize the values of arrays immediately after declaring them.
  • Simply we use ternary operator for small problems.
  • When passing parameters to methods check them that they shouldn’t be null.
  • Java has some primitives. We know that primitives contain some default values even we didn’t assign anything. But objects can have null value. So it’s better to use primitives than objects.
  • Try to avoid writing more methods in one line (chained methods).
  • Never return null from methods.
  • Since valueOf() and toString() work in same way. So use valueOf() instead of toString(). Example: In example mentioned earlier, write this line System.out.println(String.valueOf(prog));, this will print “null” but not gives error.
  • Use better comparison method than .equals(“string”).

Comment below if you have queries or found any information incorrect in above tutorial.

1 thought on “Java NullPointerException – Reasons for Exception and How to Fix?”

Leave a Comment

Your email address will not be published. Required fields are marked *