Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • 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;
}
}
}
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The array is made up of five variables that can refer to A objects. Each of these five variables is null when you construct the array. If you want five objects, then you must construct each one individually and add it to the array -- i.e.,

ob[i] = new A();

Note that rather than having exposed member variables and setting them after constructing an object, it's good practice to provide a constructor to initialize the members, i.e.,

ob[i] = new A(1, 2);
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic