This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes how do i create an 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 "how do i create an array of objects" Watch "how do i create an array of objects" New topic

how do i create an array of objects

varsha rao

Joined: Mar 06, 2006
Posts: 26
i have created an array or my own named Store. i want to create an array of objects using this class.
iv used
Store[] s=new Store[2];
then im assigning values to the elements using a for loop
for(int i=0;i<2;i++)
{ s[i].setXXX(parameter);}
but im gettin a null pointer exception here on s[i].setXXX line.
Please tell me how to correct this part. Where have i gone wrong.
Kj Reddy
Ranch Hand

Joined: Sep 20, 2003
Posts: 1704
You just declared Store[] s array object but did not initialized the s[1] & s[2] objects. You need initialize them before calling the set methods. How about modifying your for loop some thing similar to:

for(int i=0;i<2;i++)
s[i] = new Store(); // initializing
marc weber

Joined: Aug 31, 2004
Posts: 11343

You've declared an array of Store objects called s, and instantiated the array with a length of 2...

Store[] s = new Store[2];

But there are no Store objects referenced in the array. Instead, s[0] and s[1] are both null, which results in the NullPointerException when you attempt to dereference them.

You need to assign references to Store instances. For example...

s[i] = new Store();

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
varsha rao

Joined: Mar 06, 2006
Posts: 26
hi every body
thanks for helping me out, i got it working
I agree. Here's the link:
subject: how do i create an array of objects
jQuery in Action, 3rd edition