• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array of objects

 
Ajay Divakaran
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are no compilation errors, but when i run the program I get an NullPointerException in the indicated line below. How do I rectify this?

class A
{
int i,j;
}
public class ArrayObjects
{
public static void main( String args[] )
{
A ob[]= new A[5];
for( int i=0; i<5; i++ )
{
ob[i].i=1; //NullPointerException
ob[i].j=2;
}
}
}
 
Ziji (Jay) Zhang
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think that the following line,

A ob[]= new A[5];

just created 5 reference to type of A.
You have not created the Object and assign to the reference yet.

Ziji
 
John Stone
Ranch Hand
Posts: 332
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Doesn't look like SCJD problem.
 
Mark Smyth
Ranch Hand
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ajay Divakaran:
There are no compilation errors, but when i run the program I get an NullPointerException in the indicated line below. How do I rectify this?

class A
{
int i,j;
}
public class ArrayObjects
{
public static void main( String args[] )
{
A ob[]= new A[5];
for( int i=0; i<5; i++ )
{
ob[i].i=1; //NullPointerException
ob[i].j=2;
}
}
}


Not an SJCD problem but I'll answer befroe it is moved. A ob[]= new A[5]; creates and array of size 5. But the objects within the array have not been intialised so the references default to null. This is the same as the statement A ob[]= {null,null,null,null,null};
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic