wood burning stoves
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

Array Of Objects

Ajay Divakaran

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
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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
It's not a secret anymore!