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

Win a copy of Java 8 in Action this week in the Java 8 forum!
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: http://aspose.com/file-tools
subject: how do i create an array of objects
Similar Threads
An object to hold several arrays
Java code to genarate xml ,for uncontinuous data....
accepting user input into into an array
how to use c:forEach....
Update an array