Marijus Marijus - 2 months ago 7
Java Question

java.lang.NullPointerException

I'm just starting out with java and I'm trying to create an array of Dog class objects and I'm getting this error:


Exception in thread "main" java.lang.NullPointerException


at this line:

Dog[] dogsList = new Dog[7];
dogsList[4].setSize(4);

Answer

When you create an array, that's an array of references - and initially all those references are null, so they're not referring to any instances of Dog. You need to create an instance, like this:

Dog[] dogsList = new Dog[7];
dogsList[4] = new Dog();
dogsList[4].setSize(4);

Alternatively, you may already have a reference to a Dog from elsewhere:

Dog fido = new Dog();
// Other code here

dogsList[4] = fido;
dogsList[4].setSize(4);

A little background

One of the most important things to understand is the difference between objects and references. A reference is a way of getting to an object - and multiple references can refer to the same object. For example:

Dog x = new Dog();
Dog y = x;

x.setName("Fido");
System.out.println(x.getName()); // Will print "Fido"

Here, the values of the x and y variables aren't dogs... they're references to dogs (or null, which I'll come onto in a minute). The line

Dog y = x;

sets the initial value of y to the value of x - so the two variables refer to the same Dog object.

Now null is a special reference value that doesn't refer to any object. A NullPointerException is thrown if you try to dereference a null reference (usually with the . operator, but also with things like array indexing).

Arrays

When you create an array, all the elements are immediately populated with the default value for the type. For numeric types that's 0, for boolean it's false, and for char it's character 0. For any reference types (classes) it's the null reference. So when you do this:

Dog[] dogsList = new Dog[7];

that's equivalent to:

Dog[] dogsList = { null, null, null, null, null, null, null };

So in your original code, the value of dogsList[4] is null. You then try to dereference that null reference to call setSize on the referenced object... and bang! You get a NullPointerException.

There are lots of really important concepts involved in this question, so please feel free to ask for more details on any of the specific points.