This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
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

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
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: 24193

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:
subject: Array Of Objects
It's not a secret anymore!