aspose file tools*
The moose likes Beginning Java and the fly likes Array Of Objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array Of Objects" Watch "Array Of Objects" New topic
Author

Array Of Objects

Ajay Divakaran
Greenhorn

Joined: Jul 08, 2007
Posts: 22
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

Joined: Jul 08, 2003
Posts: 24184
    
  34

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);


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Array Of Objects