views:

82

answers:

7

I am writing a program in Java, in which I define a class

class Point
{
    double x;
    double y;
}

Then in a method, I define an array of points, as follows:

Point[]     line = new Point[6];

In the same method, I have the line

line[SampleSize - i + 1].x = i;

The first time this statement is hit, the value of its array index is 1; but the program throws a null pointer exception at this point.

This would seem like the correct way to index the field of an object within an array of objects. What am I doing wrong?

Thanks in advance for any suggestions.

John Doner

+3  A: 

You have to initialize the value before accessing it:

line[SampleSize - i + 1] = new Point();
Boris Pavlović
A: 

When you first create the array, it contains six null references.

Before you can interact with objects in the array, you need to create the objects, like this:

line[someIndex] = new Point();

You probably want to initialize every point in the array using a for loop.

SLaks
+3  A: 

That's because you have not created the points to put in the array

for (int index = 0; index < line.length; index++)
{
    line[index] = new Point();
}
willcodejavaforfood
A: 

http://java.sun.com/docs/books/jls/third_edition/html/arrays.html

If you note in Section 10.2 the act of creating an array simply creates the references, but not the objects. Hence the reason for your null pointer error, all of the references are given the default value, which in this case is null.

Scott
+3  A: 
Point[]     line = new Point[6];

creates an empty array, capable of holding Points. But does not hold any reference to a Point yet. All are null.

line[SampleSize - i + 1].x = i; 

tries to access x on a null.

Nivas
+1 for explaining how an array is initialized with null values
Kin U.
A: 

Although you have allocated the array, the contents of the array are null. What you need to do:

Point[] line = new Point[6];
for (int i = 0; i < line.length; i++)
{
    line[i] = new Point();
}
gregcase
+1  A: 

Just to add to Boris's answer, here is some source code

Class Point {
    double x;
    double y;
}


Point[] line = new Point[6];
for(int i = 0; i < line.length; i++) {
    line[i] = new Point();
}

    // now you can set the values, since the point's aren't null
line[0].x = 10;
line[0].y = 10;
KennyCason