java.lang.NullPointerException - What is a NullPointerException

Wikitechy | 1515 Views | java | 13 Jun 2016



  • In java NullPointerException is a RuntimeException.
  • Generally, in java a special null value can be assigned to an object reference. 
  • NullPointerException throws an exception when an application attempts to use an object reference that has null value. 

These exceptions include

  • By Calling an instance method on the object referred by a null reference.
  • Accessing or modifying an instance field of the object referred by a null reference.
  • If the reference type is an array type, taking the length of a null reference.
  • If the reference type is an array type, accessing or modifying the slots of a null reference.
  • If the reference type is a subtype of Throwable, throwing a null reference.
Object Wikitechy_obj = null;
Wikitechy_obj.toString();  // This statement will throw a NullPointerException


In java , NullPointerException is a  Runtime Exception and the Javac compiler does not force to use a try-catch block to handle it appropriately.


String comparison with literals

  • Here is the very simple way to resolve this issue using String comparison with literals.
  • In this type of case, in an application’s execution code involve the comparison between a String variable and a literal. 
  • The literal may be a String or the element of an Enum. 
  • So, instead of invoking the method from the null object, consider invoking it from the literal.

For example, observe the following 

String str = null;
if(str.equals("Test")) {
/* The code here will not be reached, as an exception will be thrown. */

Above code snippet will throw a NullPointerException. So we invoke the method from the literal, the execution flow will work correctly. 

String str = null;
if("Test".equals(str)) {
    /* Correct use case. No exception will be thrown. */

So here we call the literal of the string(Str) for checking the condition.


Check the arguments of a method

Here is another way to resolve this issue 

  • Initially Before executing the body of our own method, make sure to check whether the arguments contains any null values.
  • After that we continue with the execution of the method, only when the arguments are properly checked. Otherwise, it will throw an IllegalArgumentException and notify the calling method that something is wrong with the passed arguments.

For example, observe the following 

public static int fetchStringLenth(String s) {
if (s == null)
throw new IllegalArgumentException("The argument cannot be null");
return s.length();

So here we check the variable “s” contains any null values or not.


Use String.valueOf() method instead of toString()

  • For example, when our application’s code requires any String representation of an object it avoids using the object’s toString method. 
  • Apart from that if our object’s reference is equals to null, we will get an NullPointerException.
  • Otherwise when we use the static String.valueOf method, which does not throw any exceptions instead of that the function’s argument equals to null and just prints "null", in case the function’s argument equals to null.


Use the Ternary Operator

  • In java the ternary operator is very useful and can help us to avoid the NullPointerException. 

Syntax for ternary operator:

boolean expression ? value1 : value2;

    • The First, boolean expression is used for evaluation. 
    • If the expression is true, value1 is returned, 
    • otherwise, value2 is returned. 

Here We can use the ternary operator for handling the null pointers Exception as follows:

String message = (str == null) ? "" : str.substring(0, 10);
  • The message variable will be empty When the str reference is null.
  • Otherwise, the variable str particularly points out the actual data, So the message will retrieve the first 10 characters of it.


Working on Loops

Here is the fix to resolve the null pointer exception in loop on an array or a collection in a for each loop.

Collection<Integer> myNumbers = buildNumbers();
for (Integer myNumber : myNumbers) {
  • Consider an above example code if the object is null, 
  • If the object is null, it does not just do zero loops, it throws a null pointer exception. So don't forget this case ,which is an important procedure . 
  • And also add an if statement or return any empty collections
Collection<Integer> myNumbers = buildNumbers();
if (myNumbers != null) {
for (Integer myNumber : myNumbers) {


Minimize the use of the new Type[int] syntax for creating arrays of objects

Here is the fix to resolve the null pointer exception in an array

  • Here in the below example code: An array created by using new Object[10] and they have 10 null pointers. 
  • That's 10 more than we want, so use collections instead, or explicitly fill the array at initialization.
Object[] objects = {"JAVA", 1, new File("/usr/bin")};

And we Can re-write the following code as shown below as

Object[] objects;
objects = new Object[]{"JAVA", 1, new File("/usr/bin")};

Fixes are applicable to the following versions of java:

  • NullPointerException (Java Platform SE 7)
  • Java EE Support Patterns 

Applies to:

  • J2SE 1.3
  • J2SE 1.4
  • J2SE 5.0
  • Java SE 6
  • Java SE 7
  • Java SE 8

Related Error Tags:

  • java lang nullpointerexception in jsp
  • java lang nullpointerexception error
  • java lang nullpointerexception in servlet
  • java lang nullpointerexception in android
  • java lang nullpointerexception in eclipse
  • java lang nullpointerexception in struts
  • java lang nullpointerexception in j2me
  • how to fix java lang nullpointerexception


Bug Bounty

Join our Community