java.lang.NullPointerException With Examples

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 java standalone program as well as java web application.

java.lang.NullPointerException

java-nullpointerexception-hierarchy

NullPointerException is a runtime exception, so we don’t need to catch it in 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 length of an array that is null at runtime.

Java NullPointerException Example

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

    1. NullPointerException when calling 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 above program, it throws following NullPointerException error message.

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

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

    2. Java NullPointerException while accessing/modifying field of 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;
      	}
      }
      

      Above program throws 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 occurrence of java.lang.NullPointerException because it’s the caller who is passing null argument.

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

    4. exception-in-thread-main-java-lang-nullpointerexception
    5. 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 above program, showing NullPointerException because of throw null; statement.

      
      Exception in thread "main" java.lang.NullPointerException
      	at Temp.main(Temp.java:5)
      
    6. java.lang.NullPointerException when getting 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)
      
    7. 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)
      
    8. java.lang.NullPointerException when synchronized on null object

      
      public class Temp {
      	public static String mutex = null;
      	public static void main(String[] args) {
      		synchronized(mutex) {
      			System.out.println("synchronized block");
      		}
      	}
      }
      

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

    9. HTTP Status 500 java.lang.NullPointerException

Sometimes we get an error page being sent as java web application response with 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";
	}

Below image shows the error message thrown by web application response.

exception-in-thread-main-java-lang-nullpointerexception

Here is the exception stack trace;


HTTP Status 500 – Internal 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)

Root cause is NullPointerException in 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 java.lang.NullPointerException

java.lang.NullPointerException is an unchecked exception, so we don’t have to catch it. Usually 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 java.lang.NullPointerException

  1. Consider a code example below.
    
    public void foo(String s) {
        if(s.equals("Test")) {
    	System.out.println("test");
        }
    }
    

    Now NullPointerException can occur if the argument is being passed as null. 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. Use ternary operator as shown in 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();
            }
        }
    

    So below shows the example where 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, use them. For example contains(), containsKey() and containsValue().

That’s all about java NullPointerException. I hope it will help you in writing better code to avoid java.lang.NullPointerException as much as possible.

Reference: API Document

By admin

Leave a Reply

%d bloggers like this: