One of the most common exceptions in Java is the NullPointerException (NPE). Java beginners are often frustrated by this rather pestilent exception, since it offers little, if any help in determining the exact cause of a runtime failure. Unfortunately, most discussions that focus around the NPE devolve into the academics of pointers, and do little to rectify the situation. Instead of another such post, I thought I would offer up some friendly advice on preventing the NullPointerException altogether.
The best place to begin is with a simple definition. I recently read the following explanation, which describes the NPE in unnecessarily complicated terms on the J-Development blog:
…it simply means that you (implicitly) try to dereference a pointer that has the special reserved null value.
To be honest, I would not be able to contend with that, and I defer to the author’s experience in order to determine if it is completely accurate. I assume that it is. You will find several definitions like that as you search for information on just about any Java exception. In each instance, I suggest you start instead by reviewing the Java API specifications. In order to get a more concise picture of the NPE, I prefer to use the Java 2 Platform Std. Ed. V1.4.2.
Thrown when an application attempts to use null in a case where an object is required. These include:
- Calling the instance method of a null object.
- Accessing or modifying the field of a null object.
- Taking the length of null as if it were an array.
- Accessing or modifying the slots of null as if it were an array.
- Throwing null as if it were a Throwable value.
Applications should throw instances of this class to indicate other illegal uses of the null object.
This helps in determining why the application threw the exception, because you now have a few scenarios to test against. Calling the instance method of a null object, and accessing or modifying the field of a null object, are the most common missteps. Remember that a field in Java is just another name for a property or variable, depending on who you ask. The following code illustrates a NullPointerException based upon the previous criteria:
public class MyObject {
private String myString;
public String getMyString() {
return myString;
}
public void setMyString(String myString) {
this.myString = myString;
}
}
MyObject object = null;
String myNewString = object.getMyString();
Initializing an object to null instead of to the object’s type (in this case MyObject), does have a place in programming. However, in designing an application it is generally considered poor practice to create an object in this fashion. As you can see, I tried to access the getMyString() instance method on null, not on a MyObject. Your IDE might even suggest that this method is available through auto-complete, but do not be fooled by the fact that it is still null, and not a MyObject.
Using the same MyObject class, I will explore a similar scenario:
public class MyObject {
private String myString;
public String getMyString() {
return myString;
}
public void setMyString(String myString) {
this.myString = myString;
}
}
MyObject object = new MyObject();
String myNewString = object.getMyString();
myNewString.toUpperCase();
Hey, what gives? The object variable references a new MyObject(), so why does this return an NPE? Looking closer at the MyObject class, you can see that the myString field (property) has an “absent value”, which means that the value is actually interpreted as null by the Java Virtual Machine (JVM). The myNewString object reference variable is therefore, a null object, and executing the toUpperCase() method returns a NullPointerException.
There are two ways to fix this problem, and neither is necessarily incorrect. The first is to set a default value for the myString property. This guarantees that when another programmer gets the property, it will never return null. This is easy enough:
public class MyObject {
private String myString = "My String!";
public String getMyString() {
return myString;
}
public void setMyString(String myString) {
this.myString = myString;
}
}
Another option is to check for a null value only when a programmer calls getMyString(), and then set the default value if this condition is true. For example:
public class MyObject {
private String myString;
public String getMyString() {
if (myString == null) {
setMyString("My String!");
}
return myString;
}
public void setMyString(String myString) {
this.myString = myString;
}
}
In JSP development, the most common NullPointerException(s) happen when a programmer tries to access a session attribute, request parameter, or request attribute that was never set. These can be a bit more tricky to discover, and in general, the larger the application, the more difficult it will be to track down an NPE. Hopefully the examples above will be helpful in pinpointing the problem, and resolving the issue.
NPEs almost always mean you forgot to initialize something. Grab the line number from the exception stack trace, check for variables used on that line upon which methods are called (e.g. value.toString()). It gets a bit more tedious if there’s more than one possible culprit, but you get the picture.
There’s also a rare variety of NPE that stems from passing null values to API methods which expect otherwise. Although this technically means that you (the API user) messed something up, it also means that the API developer was incredibly lazy and didn’t check the arguments for validity (IllegalArgumentException is the proper procedure for such a case). Thankfully, these errors are far and few between in these enlightened times.
It’s worth noting that most NPEs can be detected by static analysis tools. Even Eclipse’s compiler has some basic heuristics to diagnose possible NPEs and issue warnings (or errors if desired). IntelliJ has some more advanced parsing, and tools such as FindBugs, JSure, etc provide even better coverage.
Hey Daniel,
Those are some great points — thanks for sharing. In IDEA, my method calls will usually get a highlight, and a word of caution that it could cause an NPE. I think NetBeans does the same, but I’m not as familiar with that IDE. It is indeed helpful.
I never considered that passing a null across to a method as a parameter might cause a NullPointerException. That is one that I thankfully have yet to deal with in an application. Thanks again for sharing.
“However, if the MyObject class is instantiated several times throughout the application, you will now have numerous strings on the heap (in memory) that might never be used.”
There was a bit of a misunderstanding with that statement, and it requires some clarification. You can read the comments on Reddit, or read more about String literals on Java Ranch.
[quote]There are two ways to fix this problem, and neither is necessarily incorrect. The first is to set a default value for the myString property. This guarantees that when another programmer gets the property, it will never return null.[/quote]
That is not entirely true, someone can call the setter with a null argument ;)
Hi Ronald,
That is a good point — someone could call the setter with a null argument. However, in that scenario it is likely that you set the string to null yourself for a purpose, and know about it. Intentionally setting the field to null, and then passing that object to be used by another programmer in a different piece of the application seems more malicious to me than anything.
thank you very much i almost lost hope as student in programming but now have the answer so easy and my program is working by asigning anull value to the string