Tutorial

Java NullPointerException - Detect, Fix, and Best Practices

Published on August 3, 2022
author

Pankaj

Java NullPointerException - Detect, Fix, and Best Practices

java.lang.NullPointerException is one of the most popular exceptions in java programming. Anybody working in java must have seen this popping out of nowhere in the java standalone program as well as the java web application.

java.lang.NullPointerException

java lang nullpointerexception hierarchy

NullPointerException is a runtime exception, so we don’t need to catch it in the program. NullPointerException is raised in an application when we are trying to do some operation on null where an object is required. Some of the common reasons for NullPointerException in java programs are:

  1. Invoking a method on an object instance but at runtime the object is null.
  2. Accessing variables of an object instance that is null at runtime.
  3. Throwing null in the program
  4. Accessing index or modifying value of an index of an array that is null
  5. Checking the length of an array that is null at runtime.

Java NullPointerException Examples

Let’s look at some examples of NullPointerException in java programs.

1. NullPointerException when calling an instance method

public class Temp {

	public static void main(String[] args) {

		Temp t = initT();
		
		t.foo("Hi");
		
	}

	private static Temp initT() {
		return null;
	}

	public void foo(String s) {
		System.out.println(s.toLowerCase());
	}
}

When we run the above program, it throws the following NullPointerException error message.

Exception in thread "main" java.lang.NullPointerException
	at Temp.main(Temp.java:7)

We are getting NullPointerException in the statement t.foo("Hi"); because “t” is null here.

2. Java NullPointerException while accessing/modifying field of a null object

public class Temp {

	public int x = 10;
	
	public static void main(String[] args) {

		Temp t = initT();
		
		int i = t.x;
		
	}

	private static Temp initT() {
		return null;
	}

}

The above program throws the following NullPointerException stack trace.

Exception in thread "main" java.lang.NullPointerException
	at Temp.main(Temp.java:9)

NullPointerException is being thrown in statement int i = t.x; because “t” is null here.

3. Java NullPointerException when null is passed in method argument

public class Temp {

	public static void main(String[] args) {

		foo(null);

	}

	public static void foo(String s) {
		System.out.println(s.toLowerCase());
	}
}

This is one of the most common occurrences of java.lang.NullPointerException because it’s the caller who is passing the null argument.

The below image shows the null pointer exception when the above program is executed in Eclipse IDE.

Exception in thread main java.lang.NullPointerException

4. java.lang.NullPointerException when null is thrown

public class Temp {

	public static void main(String[] args) {

		throw null;
	}

}

Below is the exception stack trace of the above program, showing NullPointerException because of throw null; statement.

Exception in thread "main" java.lang.NullPointerException
	at Temp.main(Temp.java:5)

5. NullPointerException when getting the length of null array

public class Temp {

	public static void main(String[] args) {

		int[] data = null;
		
		int len = data.length;
	}

}
Exception in thread "main" java.lang.NullPointerException
	at Temp.main(Temp.java:7)

6. NullPointerException when accessing index value of null array

public class Temp {

	public static void main(String[] args) {

		int[] data = null;
		
		int len = data[2];
	}

}
Exception in thread "main" java.lang.NullPointerException
	at Temp.main(Temp.java:7)

7. NullPointerException when synchronized on a null object

public class Temp {

	public static String mutex = null;
	
	public static void main(String[] args) {

		synchronized(mutex) {
			System.out.println("synchronized block");
		}		
	}
}

The synchronized(mutex) will throw NullPointerException because the “mutex” object is null.

8. HTTP Status 500 java.lang.NullPointerException

Sometimes we get an error page response from a java web application with an error message as “HTTP Status 500 – Internal Server Error” and root cause as java.lang.NullPointerException.

For this, I edited the Spring MVC Example project and changed the HomeController method as below.

@RequestMapping(value = "/user", method = RequestMethod.POST)
	public String user(@Validated User user, Model model) {
		System.out.println("User Page Requested");
		System.out.println("User Name: "+user.getUserName().toLowerCase());
		System.out.println("User ID: "+user.getUserId().toLowerCase());
		model.addAttribute("userName", user.getUserName());
		return "user";
	}

The below image shows the error message thrown by the web application response.

http error 500 java lang nullpointerexception

Here is the exception stack trace:

HTTP Status 500Internal Server Error

Type Exception Report

Message Request processing failed; nested exception is java.lang.NullPointerException

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
	org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
	org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
	org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
	org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause

java.lang.NullPointerException
	com.journaldev.spring.controller.HomeController.user(HomeController.java:38)
	sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	java.lang.reflect.Method.invoke(Method.java:498)

The root cause is NullPointerException in the statement user.getUserId().toLowerCase() because user.getUserId() is returning null.

How to detect java.lang.NullPointerException

Detecting NullPointerException is very easy, just look at the exception trace and it will show you the class name and line number of the exception. Then look at the code and see what could be null causing the NullPointerException. Just look at all the above examples, it’s very clear from stack trace what is causing null pointer exception.

How to fix NullPointerException

java.lang.NullPointerException is an unchecked exception, so we don’t have to catch it. The null pointer exceptions can be prevented using null checks and preventive coding techniques. Look at below code examples showing how to avoid java.lang.NullPointerException.

if(mutex ==null) mutex =""; //preventive coding
		
synchronized(mutex) {
	System.out.println("synchronized block");
}
//using null checks
if(user!=null && user.getUserName() !=null) {
System.out.println("User Name: "+user.getUserName().toLowerCase());
}
if(user!=null && user.getUserName() !=null) {
	System.out.println("User ID: "+user.getUserId().toLowerCase());
}

Coding Best Practices to avoid NullPointerException

1. Let’s consider the below function and look out for scenario causing null pointer exception.

public void foo(String s) {
    if(s.equals("Test")) {
	System.out.println("test");
    }
}

The NullPointerException can occur if the argument is being passed as null. The same method can be written as below to avoid NullPointerException.

public void foo(String s) {
	if ("Test".equals(s)) {
		System.out.println("test");
	}
}

2. We can also add null check for argument and throw IllegalArgumentException if required.

public int getArrayLength(Object[] array) {
	
	if(array == null) throw new IllegalArgumentException("array is null");
	
	return array.length;
}

3. We can use ternary operator as shown in the below example code.

String msg = (str == null) ? "" : str.substring(0, str.length()-1);

4. Use String.valueOf() rather than toString() method. For example check PrintStream println() method code is defined as below.

public void println(Object x) {
        String s = String.valueOf(x);
        synchronized (this) {
            print(s);
            newLine();
        }
    }

The below code snippet shows the example where the valueOf() method is used instead of toString().

Object mutex = null;

//prints null
System.out.println(String.valueOf(mutex));

//will throw java.lang.NullPointerException
System.out.println(mutex.toString());

5. Write methods returning empty objects rather than null wherever possible, for example, empty list, empty string, etc.

6. There are some methods defined in collection classes to avoid NullPointerException, you should use them. For example contains(), containsKey(), and containsValue().

Reference: API Document

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
April 20, 2020

Pls Resolve these two errors I got totally stuck and frustrated for two days and not get any solution pls help me to solve my issue, Error is as follow pls… ************* Error No =1:-************ HTTP Status 500 – Internal Server Error Type Exception Report Message null Description The server encountered an unexpected condition that prevented it from fulfilling the request. Exception java.lang.NumberFormatException: null java.lang.Integer.parseInt(Unknown Source) java.lang.Integer.parseInt(Unknown Source) com.ServletAdd.AddServlet.service(AddServlet.java:13) javax.servlet.http.HttpServlet.service(HttpServlet.java:741) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) Note The full stack trace of the root cause is available in the server logs ******** Error No= 2:-**************** HTTP Status 404 – Not Found Type Status Report Message /ServletInterfaceDemo/NewFile.html Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

- Nafees Kausar

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    June 23, 2019

    Causes bad lag on joining minecraft 1.4.2 servers. Error executing task on Client java.lang.NullPointerException at csx.d(SourceFile:199) at dhk.a(SourceFile:1990) at my.a(SourceFile:122) at my.a(SourceFile:16) at kc.a(SourceFile:15) at agk.h(SourceFile:135) at ago.h(SourceFile:23) at agk.p(SourceFile:114) at agk.bf(SourceFile:99) at cvk.e(SourceFile:915) at cvk.b(SourceFile:411) at net.minecraft.client.main.Main.main(SourceFile:154)

    - joe

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      October 16, 2018

      thank’s it really helps !!

      - errami

        Try DigitalOcean for free

        Click below to sign up and get $200 of credit to try our products over 60 days!

        Sign up

        Join the Tech Talk
        Success! Thank you! Please check your email for further details.

        Please complete your information!

        Featured on Community

        Get our biweekly newsletter

        Sign up for Infrastructure as a Newsletter.

        Hollie's Hub for Good

        Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

        Become a contributor

        Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

        Welcome to the developer cloud

        DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

        Learn more