Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I created a class Car. It includes a location, a double array size 2. I'm trying to create an array of Cars. Here is what I have:

Car[] cars;
cars = new Car[3];

cars[0].location = new double[]{1,6};
cars[1].location = new double[]{10,30};
cars[2].location = new double[]{20,7};

I get an error where I try to declare the location: NullPointerException. How do I resolve this?

share|improve this question
3  
You haven't initialized the elements in the array. –  Sotirios Delimanolis Feb 2 '14 at 2:07

1 Answer 1

up vote 4 down vote accepted

You need to create reference variables for the objects in the array. Your original code simply initializes a Cars array of size 3, but doesn't put any objects inside.

Car[] cars;
cars = new Cars[3];

for (int i=0; i<3; i+=1) {
    cars[i] = new Car();
}

cars[0].location = new double[]{1,6};
cars[1].location = new double[]{10,30};    
cars[2].location = new double[]{20,7};
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.