What is a NullPointerException, and how do I fix it?


What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?



What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?



This question's answers are a collaborative effort: if you see something that can be improved, just edit the answer to improve it! No additional answers can be added here



When you declare a reference variable (i.e. an object) you are really creating a pointer to an object. Consider the following code where you declare a variable of primitive type int:



In this example, the variable x is an int and Java will initialize it to 0 for you. When you assign it to 10 in the second line your value 10 is written into the memory location pointed to by x.



But, when you try to declare a reference type something different happens. Take the following code:



The first line declares a variable named num, but, it does not contain a primitive value. Instead, it contains a pointer (because the type is Integer which is a reference type). Since you did not say as yet what to point to Java sets it to null, meaning "I am pointing at nothing".



In the second line, the new keyword is used to instantiate (or create) an object of type Integer and the pointer variable num is assigned this object. You can now reference the object using the dereferencing operator . (a dot).



The Exception that you asked about occurs when you declare a variable but did not create an object. If you attempt to dereference num BEFORE creating the object you get a NullPointerException. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized" but sometimes you write code that does not directly create the object.



For instance, you may have a method as follows:



In which case you are not creating the object obj, rather assuming that it was created before the doSomething method was called. Unfortunately, it is possible to call the method like this:



In which case obj is null. If the method is intended to do something to the passed-in object, it is appropriate to throw the NullPointerException because it's a programmer error and the programmer will need that information for debugging purposes.



Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething could be written as:



Finally, How to pinpoint the exception & cause using Stack Trace



NullPointerExceptions are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException. These are the most common, but other ways are listed on the NullPointerException javadoc page.



Probably the quickest example code I could come up with to illustrate a NullPointerException would be:



On the first line inside main, I'm explicitly setting the Object reference obj equal to null. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NullPointerException because there is no code to execute in the location that the reference is pointing.



(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere, which is subtly different than pointing to a location that happens to be invalid.)



A good place to start is the JavaDocs. They have this covered:



Thrown when an application attempts to use null in a case where an
object is required. These include:



Applications should throw instances of this class to indicate other
illegal uses of the null object.



It is also the case that if you attempt to use a null reference with synchronized, that will also throw this exception, per the JLS:



So you have a NullPointerException. How do you fix it? Let's take a simple example which throws a NullPointerException:



Identify the null values



The first step is identifying exactly which values are causing the exception. For this, we need to do some debugging. It's important to learn to read a stacktrace. This will show you where the exception was thrown:



Here, we see that the exception is thrown on line 13 (in the printString method). Look at the line and check which values are null by
adding logging statements or using a debugger. We find out that s is null, and calling the length method on it throws the exception. We can see that the program stops throwing the exception when s.length() is removed from the method.



Trace where these values come from



Next check where this value comes from. By following the callers of the method, we see that s is passed in with printString(name) in the print() method, and this.name is null.



Trace where these values should be set



Where is this.name set? In the setName(String) method. With some more debugging, we can see that this method isn't called at all. If the method was called, make sure to check the order that these methods are called, and the set method isn't called after the print method.



This is enough to give us a solution: add a call to printer.setName() before calling printer.print().



The variable can have a default value (and setName can prevent it being set to null):



Either the print or printString method can check for null, for example:



Or you can design the class so that name always has a non-null value:



See also:



If you tried to debug the problem and still don't have a solution, you can post a question for more help, but make sure to include what you've tried so far. At a minimum, include the stacktrace in the question, and mark the important line numbers in the code. Also, try simplifying the code first (see SSCCE).



As you should know, Java types are divided into primitive types (boolean, int, etc.) and reference types. Reference types in Java allow you to use the special value null which is the Java way of saying "no object".



A NullPointerException is thrown at runtime whenever your program attempts to use a null as if it was a real reference. For example, if you write this:



the statement labelled "HERE" is going to attempt to run the length() method on a null reference, and this will throw a NullPointerException.



There are many ways that you could use a null value that will result in a NullPointerException. In fact, the only things that you can do with a null without causing an NPE are:



Suppose that I compile and run the program above:



First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a runtime error. (Some IDEs may warn your program will always throw an exception ... but the standard javac compiler doesn't.)



Second observation: when I run the program, it outputs two lines of "gobbledy-gook". WRONG!! That's not gobbledy-gook. It is a stacktrace ... and it provides vital information that will help you track down the error in your code, if you take the time to read it carefully.



So let's look at what it says:



The first line of the stack trace tells you a number of things:



The second line is the most important one in diagnosing an NPE.



This tells us a number of things:



If you count the lines in the file above, line 4 is the one that I labeled with the "HERE" comment.



Note that in a more complicated example, there will be lots of lines in the NPE stack trace. But you can be sure that the second line (the first "at" line) will tell you where the NPE was thrown1.



In short the stack trace will tell us unambiguously which statement of the program has thrown the NPE.



1 - Not quite true. There are things called nested exceptions...



This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code and the relevant API documentation.



Let's illustrate with the simple example (above) first. We start by looking at the line that the stack trace has told us is where the NPE happened:



How can that throw an NPE?



In fact there is only one way: it can only happen if foo has the value null. We then try to run the length() method on null and .... BANG!



But (I hear you say) what if the NPE was thrown inside the length() method call?



Well, if that happened, the stack trace would look different. The first "at" line would say that the exception was thrown in some line in the java.lang.String class, and line 4 of Test.java would be the second "at" line.



So where did that null come from? In this case it is obvious, and it is obvious what we need to do to fix it. (Assign a non-null value to foo.)



OK, so let's try a slightly more tricky example. This will require some logical deduction.



So now we have two "at" lines. The first one is for this line:



and the second one is for this line:



Looking at the first line, how could that throw an NPE? There are two ways:



Next, we need to figure out which of those scenarios explains what is actually happening. We will start by exploring the first one:



Where does bar come from? It is a parameter to the test method call, and if we look at how test was called, we can see that it comes from the foo static variable. In addition, we can see clearly that we initialized foo to a non-null value. That is sufficient to tentatively dismiss this explanation. (In theory, something else could change foo to null ... but that is not happening here.)



So what about our second scenario? Well, we can see that pos is 1, so that means that foo[1] must be null. Is that possible?



Indeed it is! And that is the problem. When we initialize like this:



we allocate a String with two elements that are initialized to null. After that, we have not changed the contents of foo ... so foo[1] will still be null.



It's like you are trying to access an object which is null. Consider below example:



At this time you have just declared this object but not initialized or instantiated. And whenever you try to access any property or method in it, it will throw NullPointerException which makes sense.



See this below example as well:



A null pointer exception is thrown when an application attempts to use null in a case where an object is required. These include:



Applications should throw instances of this class to indicate other illegal uses of the null object.



Reference: http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html



A NULL pointer is one that points to nowhere. When you dereference a pointer p, you say "give me the data at the location stored in "p". When p is a null pointer, the location stored in p is nowhere, you're saying "give me the data at the location 'nowhere'". Obviously, it can't do this, so it throws a NULL pointer exception.



In general, it's because something hasn't been initialized properly.



A lot of explanations are already present to explain how it happens and how to fix it, but you should also follow best practices to avoid NullPointerException at all.



See also:
A good list of best practices



I would add, very important, make a good use of the final modifier.
Using the "final" modifier whenever applicable in Java



Summary:



A null pointer exception is an indicator that you are using an object without initializing it.



For example, below is a student class which will use it in our code.



The below code gives you a null pointer exception.



Because you are using Obj_Student, but you forgot to initialize it like in the
correct code shown below:



In Java, everything is in the form of a class.



If you want to use any object then you have two phases:



Example:



Same for the array concept



If you are not giving the initialization section then the NullpointerException arise.



In Java all the variables you declare are actually "references" to the objects (or primitives) and not the objects themselves.



When you attempt to execute one object method, the reference asks the living object to execute that method. But if the reference is referencing NULL (nothing, zero, void, nada) then there is no way the method gets executed. Then the runtime let you know this by throwing a NullPointerException.



Your reference is "pointing" to null, thus "Null -> Pointer".



The object lives in the VM memory space and the only way to access it is using this references. Take this example:



This an important thing to know - when there are no more references to an object (in the example above when reference and otherReference point to null) then the object is "unreachable". There is no way we can work with it, so this object is marked for to be garbage collected, and at some point, the VM will free the memory used by this object and will allocate another.



Another occurrence of a NullPointerException occurs when one declares an object array, then immediately tries to dereference elements inside of it.



This particular NPE can be avoided if the comparison order is reversed; namely, use .equals on a guaranteed non-null object.



All elements inside of an array are initialized to their common initial value; for any type of object array, that means that all elements are null.



You must initialize the elements in the array before accessing or dereferencing them.

Popular posts from this blog

大跃进

马相伯