Why do I get a nullPointerException here

05.03 NullPointerException

One is thrown whenever an object is used instead of an instance. This is always the case when the value has been assigned to a variable of an object and this object is accessed accordingly. See Chapter 04.02 Objects.

One is thrown in the following cases. At the …

  • Calling a method of an object
  • Access to an attribute of an object
  • Get the length of an array that is equal
  • Access to an element of an array that is the same
  • Throw one that is the same

None will be thrown in the following cases:

At the comparison with an object:

Object obj = new Object (); Object nObj = null; if (nObj == obj) {// not equal to} if (nObj == zero) {// nObj equal to zero}

When comparing two objects with equalsif it has been correctly overwritten (see Chapter 04.03.11 Special methods (equals, hashCode and toString)) and the object whose method is called is not the same.

Object obj = new Object (); Object nObj = null; if (obj.equals (nObj)) {// equals}

When an object is replaced by a Method returned becomes.

public object getObj () {return null; } public Object getObj2 () {Object obj = null; return obj; }

Since this is not a checked exception, it can be thrown without extending the clause. The StackTrace one (or abbreviated also NPE) looks something like this:

As can be seen in the error message, the error was thrown in line 6. This is the associated code:

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

Common causes of failure

  1. An object attribute was set to when it was declared and was not initialized before the first access.
  2. A method is used to assign an object to a variable. Unfortunately, the method returns (due to an unfavorable constellation or an error) instead of an object.
  3. An object attribute has the same name as a local variable. When accessing, the local variable (which is still there) is accidentally accessed instead of the object attribute.


To fix one, you need to first find out which object is the same. You can use the error message to locate the associated line. Test in your program (e.g. with a debugger or by outputting the variables on the console via) which object is. Next you need to find out why the object is. To do this, go backwards through your source code until you have found the assignment of to this object. Finally, you have to analyze why the object was assigned at this point or why the object was not instantiated again later using. You then have to react accordingly - either by re-instantiating the object, preventing the assignment of hotcasinosonline.net, or intercepting the case if the object is the same.