File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
Author

how do i create an array of objects

varsha rao
Greenhorn

Joined: Mar 06, 2006
Posts: 26
hello,
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
s[i].setXXX(parameter);
}
marc weber
Sheriff

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
sscce.org
varsha rao
Greenhorn

Joined: Mar 06, 2006
Posts: 26
hi every body
thanks for helping me out, i got it working
regards
varsha
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: how do i create an array of objects
 
Similar Threads
An object to hold several arrays
how to use c:forEach....
Java code to genarate xml ,for uncontinuous data....
accepting user input into into an array
Update an array