Exception in thread "main" java.lang.NullPointerException is one of the common problems and Java error that you will face when developing Java or Java EE applications. This Java Exception has been around since early JDK days e.g. JDK 1.0.
If you run the program as is, you will see the output as per below:
Conclusion and best practices
Most of you probably have seen and resolve this problem multiple times so this article is mainly dedicated for individuals new in Java or interested to revisit this Java Exception.
java.lang.NullPointerException: Overview
NullPointerException is a runtime Exception thrown by the JVM when your application code, other referenced API(s) or middleware (Weblogic, WAS, JBoss...) encounters the following conditions:
- Attempting to invoke an instance method of a null object
- Attempting to access or modify a particular field of a null object
- Attempting to obtain the length of such null object as an array
java.lang.NullPointerException: Sample Java program
** A YouTube tutorial video is now available.
It is always best to learn with examples and sample Java programs. The program below is a very simple Java program generating a java.lang.NullPointerException. Please simply copy/paste and run the program with the IDE of your choice (Eclipse IDE was used for this example).
It is always best to learn with examples and sample Java programs. The program below is a very simple Java program generating a java.lang.NullPointerException. Please simply copy/paste and run the program with the IDE of your choice (Eclipse IDE was used for this example).
package org.ph.java.courses;
/**
* NullPointerExceptionSampleProgram
* @author Pierre-Hugues Charbonneau
*
*/
public class NullPointerExceptionSampleProgram {
private String field1 = null;
private String field2 = null;
public String getField1() {
return field1;
}
public void setField1(String field1) {
this.field1 = field1;
}
public String getField2() {
return field2;
}
public void setField2(String field2) {
this.field2 = field2;
}
/**
* @param args
*/
public static void main(String[] args) {
try {
// Create a fresh object instance
NullPointerExceptionSampleProgram objectInstance =
new NullPointerExceptionSampleProgram();
// Initialize field1...
objectInstance.setField1("field1Value");
// reset our object instance to null
objectInstance = null;
// Now initialize field2...BOOM! >> NullPointerException!
objectInstance.setField2("field1Value2");
} catch (Throwable any) {
System.out.println("Java ERROR: "+any);
any.printStackTrace();
}
}
}
If you run the program as is, you will see the output as per below:
java.lang.NullPointerException
at org.ph.java.courses.NullPointerExceptionSampleProgram.main
(NullPointerExceptionSampleProgram.java:47)
Java ERROR: java.lang.NullPointerException
As you can see in our example, the NullPointerException is thrown when attempting to execute the setField2() method against our objectInstance which is now null.
The JVM will typically show you the line of code (line 47 in this example) where the NullPointerException is triggered. This is critical data since it allows you to trace back the problem in your application Java code at this particular line of code of the affected Java class.
java.lang.NullPointerException: Resolution strategies
Now that you understand this problem, it is now time to resolve it. Complexity of the resolution will depend of the context of your problem since NullPointerException can be a problem by itself or simply a symptom of another problem (no data returned from a Web Service call etc.). Regardless of the context & root cause, you must shield your Java code and add proper error handling and null check validations when applicable:
- Review the java.lang.NullPointerException Stack Trace and determine where the Exception is triggered (your application code, third part API, middleware software such as Weblogic etc.) and extract the line #
- If problem is at your application code then a code walkthrough will be required. If problem is found from third party API and / or middleware, my recommendation is to first review your referenced code and determine if it could be indirectly be the source of the problem e.g. passing a null value to a third part API method etc.
- If problem found within your application code, then attempt to determine which Object instance is null and causing the problem. You will need to modify your code in order to add proper null check validations and proper logging so you can understand the source of the null value as well
Now back at our example, a simple validation and logging can be added as per below:
** Please note that logging should be done via standard logging framework such as Log4J **
// Now Initialize field2 but only if objectInstance is not null
if (objectInstance != null) {
objectInstance.setField2("field1Value2");
} else{
System.out.println("objectInstance is null, do not attempt to initialize field2");
}
Conclusion and best practices
Best practices include:
- Add proper null check validations before attempting to use an object Instance method e.g. if (objectInstance != null) { objectInstance.method(); }
- When a null object is found, please add proper logging so you can pinpoint the root cause / source of the null value
- Avoid too many object instance method calls on a single line as it will increase diagnostic complexity in the event of a NullPointerException e.g. avoid calls like this below unless properly checked for null prior to the call:
objectInstance.method(objectInstance2.getData(), objectInstance3.getData(),objectInstance4.getData());
I hope this article has helped you to understand what is null in Java.
Please feel free to add any comment or question if you are still struggling with a java.lang.NullPointerException problem.