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
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;
- Invoking a method on an object instance but at runtime the object is null.
- Accessing variables of an object instance that is null at runtime.
- Throwing null in the program
- Accessing index or modifying value of an index of an array that is null
- Checking length of an array that is null at runtime.
Java NullPointerException Example
Let’s look at some examples of NullPointerException in java programs.
-
-
NullPointerException when calling instance method
1234567891011121314public 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.
1234Exception in thread "main" java.lang.NullPointerExceptionat Temp.main(Temp.java:7)We are getting NullPointerException in statement
t.foo("Hi");
because “t” is null here. -
Java NullPointerException while accessing/modifying field of null object
123456789101112public 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.
1234Exception in thread "main" java.lang.NullPointerExceptionat Temp.main(Temp.java:9)NullPointerException is being thrown in statement
int i = t.x;
because “t” is null here. -
Java NullPointerException when null is passed in method argument
12345678910public 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.
-
java.lang.NullPointerException when null is thrown
1234567public 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.1234Exception in thread "main" java.lang.NullPointerExceptionat Temp.main(Temp.java:5) -
java.lang.NullPointerException when getting length of null array
12345678public class Temp {public static void main(String[] args) {int[] data = null;int len = data.length;}}1234Exception in thread "main" java.lang.NullPointerExceptionat Temp.main(Temp.java:7) -
NullPointerException when accessing index value of null array
12345678public class Temp {public static void main(String[] args) {int[] data = null;int len = data[2];}}1234Exception in thread "main" java.lang.NullPointerExceptionat Temp.main(Temp.java:7) -
java.lang.NullPointerException when synchronized on null object
12345678910public 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. -
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.
1 2 3 4 5 6 7 8 9 10 |
@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.
Here is the exception stack trace;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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
.
1 2 3 4 5 6 |
if(mutex ==null) mutex =""; //preventive coding synchronized(mutex) { System.out.println("synchronized block"); } |
1 2 3 4 5 6 7 8 9 |
//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
- Consider a code example below.
1234567public 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.
1234567public void foo(String s) {if ("Test".equals(s)) {System.out.println("test");}} - We can also add null check for argument and throw
IllegalArgumentException
if required.
123456public int getArrayLength(Object[] array) {if(array == null) throw new IllegalArgumentException("array is null");return array.length;} - Use ternary operator as shown in below example code.
123String msg = (str == null) ? "" : str.substring(0, str.length()-1); - Use
String.valueOf()
rather thantoString()
method. For example check PrintStream println() method code is defined as below.
123456789public 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().
1234567Object mutex = null;//prints nullSystem.out.println(String.valueOf(mutex));//will throw java.lang.NullPointerExceptionSystem.out.println(mutex.toString()); - Write methods returning empty objects rather than null wherever possible, for example empty list, empty string etc.
- 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