Reputation: 7458
I used to write my program codes in C and now moving to Java trying to define a simple struct and create and array of it in the code below, however the run-time exception occurs Exception in thread "main" java.lang.NullPointerException at CPoint.main(CPoint.java:19) I know i have to allocate memory to my array somewhere, but do not know where. Any help will be appreciated:
public class CPoint {
public int x;
public int y;
public CPoint(int size){
System.out.println("Constructor1 is called");
}
public CPoint(){
System.out.println("Constructor2 is called");
}
public static void main(String[] args){
CPoint [] p = new CPoint [3];
p[0].x=90;p[0].y=80; // this is line 19
System.out.println(p[0].x);
}
}
PS. I would like to allocate memory somewhere in the class CPoint , not in main, if possible I would like to keep the main() code as simple as possible
Upvotes: 1
Views: 12585
Reputation: 57316
You need to allocate each of the objects in the array:
public static void main(String[] args){
CPoint [] p = new CPoint [3];
p[0] = new CPoint();
p[0].x=90;p[0].y=80;
System.out.println(p[0].x);
}
Edit: You can wrap array initialisation into a static method in the class - essentially an array factory method:
public class CPoint {
public int x;
public int y;
public CPoint() { System.out.println("Inside constructor 1"); }
public static CPoint[] CPointSet(int size) {
CPoint[] p= new CPoint[size];
for(int i=0; i<size; i++)
p[i] = new CPoint();
return p;
}
public static void main(String[] args) {
CPoint[] p = CPoint.CPointSet(3);
p[0].x = 90;
p[0].y = 80;
}
}
Upvotes: 2
Reputation: 1490
Agree to Moonbeam, new CPoint[3] will create an Array object, which in fact an array of references (that's different to C), and all three elements refer to 'null' initially. No memory (for CPoint struct) is allocated util you new some CPoint objects.
You can initialize arrays in this concise way:
CPoint[] p = { new CPoint(), new CPoint(), new CPoint() }
p[0].x=90; p[0].y=80;
System.out.println(p[0].x);
Upvotes: 0
Reputation: 533530
You need to create your objects before your use them.
CPoint [] p = new CPoint [3];
p[0] = new CPoint();
Upvotes: 0