I’m just learning java out of a what seems to be an excellent book, but I’m having a problem following one of the examples. In the code that follows, I’m obviously missing a step in using a member variable of a simple class. What am I doing wrong?
Here’s the code:
class Dog {
String name;
String color;
}
class DogsExample {
public static void main(String[] args) {
Dog [] myDogs = new Dog[3];
myDogs[0].name = "Rover";
}
}
When I run this program, it causes a null pointer exception where I assign a value to the name member variable:
$ java DogsExample
Exception in thread "main" java.lang.NullPointerException
at DogsExample.main(DogsExample.java:11)
Why can’t I do this?
In Java, when you create an array, it is automatically filled with
nullvalues (unless you are using an array of primitives, in which case the array is filled with zeros).What you are doing is accessing a null value and trying to get a field of it. Your code is essentially performing
null.name = "Rover". SetmyDogs[0]to a valid instance, or you’ll get a NullPointerException.You can create a new instance of Dog in the element like this:
Or you can do it when you make the array, like this: