46651

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

Question:

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?

Answer1:

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:

int x; x = 10;

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:

Integer num; num = new Integer(10);

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 "<strong>I am pointing at nothing</strong>".

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:

public void doSomething(SomeObject obj) { //do something to obj }

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:

doSomething(null);

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 <strong>null parameter</strong> and behave differently. You should also explain this in the documentation. For example, doSomething could be written as:

/** * @param obj An optional foo for ____. May be null, in which case * the result will be ____. */ public void doSomething(SomeObject obj) { if(obj != null) { //do something } else { //do something else } }

Finally, <a href="https://stackoverflow.com/q/3988788/2775450" rel="nofollow">How to pinpoint the exception & cause using Stack Trace</a>

Answer2:

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 <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html" rel="nofollow">NullPointerException</a> javadoc page.

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

public class Example { public static void main(String[] args) { Object obj = null; obj.hashCode(); } }

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 <em>anywhere</em>, which is subtly different than pointing to a location that happens to be invalid.)

Answer3:

What is a NullPointerException?

A good place to start is the <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html" rel="nofollow">JavaDocs</a>. They have this covered:

<blockquote>

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

<ul><li>Calling the instance method of a null object.</li> <li>Accessing or modifying the field of a null object.</li> <li>Taking the length of null as if it were an array.</li> <li>Accessing or modifying the slots of null as if it were an array.</li> <li>Throwing null as if it were a Throwable value.</li> </ul>

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

</blockquote>

It is also the case that if you attempt to use a null reference with synchronized, that will also throw this exception, <a href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.19" rel="nofollow">per the JLS</a>:

<blockquote> SynchronizedStatement: synchronized ( Expression ) Block <ul><li>Otherwise, if the value of the Expression is null, a NullPointerException is thrown.</li> </ul></blockquote>

How do I fix it?

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

public class Printer { private String name; public void setName(String name) { this.name = name; } public void print() { printString(name); } private void printString(String s) { System.out.println(s + " (" + s.length() + ")"); } public static void main(String[] args) { Printer printer = new Printer(); printer.print(); } }

<strong>Identify the null values</strong>

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

Exception in thread "main" java.lang.NullPointerException at Printer.printString(Printer.java:13) at Printer.print(Printer.java:9) at Printer.main(Printer.java:19)

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 <em>logging statements</em> or using a <em>debugger</em>. 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.

<strong>Trace where these values come from</strong>

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.

<strong>Trace where these values should be set</strong>

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 <em>order</em> that these methods are called, and the set method isn't called <em>after</em> the print method.

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

Other fixes

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

private String name = "";

Either the print or printString method can <em>check for null</em>, for example:

printString((name == null) ? "" : name);

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

public class Printer { private final String name; public Printer(String name) { this.name = Objects.requireNonNull(name); } public void print() { printString(name); } private void printString(String s) { System.out.println(s + " (" + s.length() + ")"); } public static void main(String[] args) { Printer printer = new Printer("123"); printer.print(); } }

<strong>See also:</strong>

<ul><li><a href="https://stackoverflow.com/questions/271526/avoiding-null-statements-in-java" rel="nofollow">Avoiding “!= null” statements in Java?</a></li> </ul>

I still can't find the problem

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, <strong>include the stacktrace</strong> in the question, and <strong>mark the important line numbers</strong> in the code. Also, try simplifying the code first (see <a href="http://sscce.org/" rel="nofollow">SSCCE</a>).

Answer4:

<h2>Question: What causes a NullPointerException (NPE)?</h2>

As you should know, Java types are divided into <em>primitive types</em> (boolean, int, etc.) and <em>reference types</em>. 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:

public class Test { public static void main(String[] args) { String foo = null; int length = foo.length(); // HERE } }

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 <em>can</em> do with a null without causing an NPE are:

<ul><li>assign it to a reference variable or read it from a reference variable,</li> <li>assign it to an array element or read it from an array element (provided that array reference itself is non-null!),</li> <li>pass it as a parameter or return it as a result, or</li> <li>test it using the == or != operators, or instanceof.</li> </ul><h2>Question: How do I read the NPE stacktrace?</h2>

Suppose that I compile and run the program above:

$ javac Test.java $ java Test Exception in thread "main" java.lang.NullPointerException at Test.main(Test.java:4) $

First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a <em>runtime</em> 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". <strong>WRONG!!</strong> That's not gobbledy-gook. It is a stacktrace ... and it provides <em>vital information</em> 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:

Exception in thread "main" java.lang.NullPointerException

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

<ul><li>It tells you the name of the Java thread in which the exception was thrown. For a simple program with one thread (like this one), it will be "main". Let's move on ...</li> <li>It tells you the full name of the exception that was thrown; i.e. java.lang.NullPointerException.</li> <li>If the exception has an associated error message, that will be output after the exception name. NullPointerException is unusual in this respect, because it rarely has an error message.</li> </ul>

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

at Test.main(Test.java:4)

This tells us a number of things:

<ul><li>"at Test.main" says that we were in the main method of the Test class.</li> <li>"Test.java:4" gives the source filename of the class, AND it tells us that the statement where this occurred is in line 4 of the file.</li> </ul>

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 thrown<sup>1</sup>.

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

<sup>1 - Not quite true. There are things called nested exceptions...</sup>

<h2>Question: How do I track down the cause of the NPE exception in my code?</h2>

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:

int length = foo.length(); // HERE

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 <em>logical deduction</em>.

public class Test { private static String[] foo = new String[2]; private static int test(String[] bar, int pos) { return bar[pos].length(); } public static void main(String[] args) { int length = test(foo, 1); } } $ javac Test.java $ java Test Exception in thread "main" java.lang.NullPointerException at Test.test(Test.java:6) at Test.main(Test.java:10) $

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

return args[pos].length();

and the second one is for this line:

int length = test(foo, 1);

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

<ul><li>If the value of bar is null then bar[pos] will throw an NPE.</li> <li>If the value of bar[pos] is null then calling length() on it will throw an NPE.</li> </ul>

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 <em>change</em> 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:

private static String[] foo = new String[2];

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

Answer5:

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

TypeA objA;

At this time you have just <strong>declared</strong> this object but not <strong>initialized or instantiated</strong>. 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:

String a = null; System.out.println(a.toString()); // NullPointerException will be thrown

Answer6:

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

<ol><li>Calling the instance method of a null object.</li> <li>Accessing or modifying the field of a null object.</li> <li>Taking the length of null as if it were an array.</li> <li>Accessing or modifying the slots of null as if it were an array.</li> <li>Throwing null as if it were a Throwable value. </li> </ol>

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

Reference: <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html" rel="nofollow">http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html</a>

Answer7:

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.

Answer8:

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

See also: <a href="http://javarevisited.blogspot.com/2013/05/ava-tips-and-best-practices-to-avoid-nullpointerexception-program-application.html" rel="nofollow">A good list of best practices</a>

I would add, very important, make a good use of the final modifier. <a href="https://stackoverflow.com/questions/137868/using-final-modifier-whenever-applicable-in-java" rel="nofollow">Using the "final" modifier whenever applicable in Java</a>

<strong>Summary:</strong>

<ol><li>Use the final modifier to enforce good initialization.</li> <li>Avoid returning null in methods, for example returning empty collections when applicable.</li> <li>Use annotations @NotNull and @Nullable</li> <li>Fail fast and use asserts to avoid propagation of null objects through the whole application when they shouldn't be null.</li> <li>Use equals with a known object first: if("knownObject".equals(unknownObject)</li> <li>Prefer valueOf() over toString().</li> <li>Use null safe StringUtils methods StringUtils.isEmpty(null).</li> </ol>

Answer9:

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.

public class Student { private int id; public int getId() { return this.id; } public setId(int newId) { this.id = newId; } }

The below code gives you a null pointer exception.

public class School { Student obj_Student; public School() { try { obj_Student.getId(); } catch(Exception e) { System.out.println("Null Pointer "); } } }

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

public class School { Student obj_Student; public School() { try { obj_Student = new Student(); obj_Student.setId(12); obj_Student.getId(); } catch(Exception e) { System.out.println("Null Pointer "); } } }

Answer10:

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

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

<ol><li>Declare</li> <li>Initialization</li> </ol>

Example:

<ul><li>Declaration: Object a;</li> <li>Initialization: a=new Object();</li> </ul>

Same for the array concept

<ul><li>Declaration: Item i[]=new Item[5];</li> <li>Initialization: i[0]=new Item();</li> </ul>

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

Answer11:

In <a href="http://en.wikipedia.org/wiki/Java_%28programming_language%29" rel="nofollow">Java</a> 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:

public class Some { private int id; public int getId(){ return this.id; } public setId( int newId ) { this.id = newId; } }

And on another place in your code:

Some reference = new Some(); // Point to a new object of type Some() Some otherReference = null; // Initiallly this points to NULL reference.setId( 1 ); // Execute setId method, now private var id is 1 System.out.println( reference.getId() ); // Prints 1 to the console otherReference = reference // Now they both point to the only object. reference = null; // "reference" now point to null. // But "otherReference" still point to the "real" object so this print 1 too... System.out.println( otherReference.getId() ); // Guess what will happen System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...

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

Answer12:

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

String[] phrases = new String[10]; String keyPhrase = "Bird"; for(String phrase : phrases) { System.out.println(phrase.equals(keyPhrase)); }

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

All elements inside of an array <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5" rel="nofollow">are initialized to their common initial value</a>; for any type of object array, that means that all elements are null.

You <em>must</em> initialize the elements in the array <em>before</em> accessing or dereferencing them.

String[] phrases = new String[] {"The bird", "A bird", "My bird", "Bird"}; String keyPhrase = "Bird"; for(String phrase : phrases) { System.out.println(phrase.equals(keyPhrase)); }

Recommend

  • angular Js ui router nested views
  • images are not showing up in paint component
  • PHP's SimpleXMLElement analog for Node.js [closed]
  • Document.body doesn't exist. Modernizr hyphens test needs it [closed]
  • Best way to handle offline and online development with Git
  • Jest - Cannot find module 'setupDevtools' from 'setup.js'
  • How to prevent cross domain issues by proxying in IIS?
  • Performance difference between accessing local and class member variables
  • How to prompt user that edits have been made upon changing pages or sorting in Kendo Grid
  • Access PCF DEV from external machine on same network as host
  • Change border corlor of NSTableView
  • proxy request in node.js / express
  • How to protect the mp3 file from read or copy on Android?
  • Return to second to last URL in MVC (return View with previous filter conditions applied)?
  • Nested projects in multiproject visual studio templates
  • Does Mobilefirst provide a provision to access web services directly?
  • Excel's Macro-Recorder usage
  • How to use carriage return with multiple line?
  • java.lang.NoClassDefFoundError: com.parse.Parse$Configuration$Builder on below Lollipop versions
  • C# - Serializing and deserializing static member
  • Apache 2.4 and php-fpm does not trigger apache http basic auth for php pages
  • Sending data from AppleScript to FileMaker records
  • Why is the timeout on a windows udp receive socket always 500ms longer than set by SO_RCVTIMEO?
  • Weird JavaScript statement, what does it mean?
  • retrieve vertices with no linked edge in arangodb
  • using conditional logic : check if record exists; if it does, update it, if not, create it
  • How to include full .NET prerequisite for Wix Burn installer
  • Buffer size for converting unsigned long to string
  • Codeigniter doesn't let me update entry, because some fields must be unique
  • python regex in pyparsing
  • Hits per day in Google Big Query
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Change div Background jquery
  • need help with bizarre java.net.HttpURLConnection behavior
  • Android Google Maps API OnLocationChanged only called once
  • How to get Windows thread pool to call class member function?
  • apache spark aggregate function using min value
  • Is it possible to post an object from jquery to bottle.py?
  • Does armcc optimizes non-volatile variables with -O0?
  • How can I use threading to 'tick' a timer to be accessed by other threads?