Marijus Marijus - 1 year ago 104
Java Question


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];

Answer Source

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();

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

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

dogsList[4] = fido;

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;

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).


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download