aspose file tools
The moose likes Beginning Java and the fly likes Creating array of objects Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Creating array of objects" Watch "Creating array of objects" New topic
Author

Creating array of objects

Kaush Kane
Ranch Hand

Joined: May 22, 2006
Posts: 37
Hi All,
I am trying to create an array of objects of a particular class in the following manner
class objectArray {
public static void main(String[] args) {
String[] args = {"abc", "123"}
CreateObjArr[args.length] obj;
for (int i=0;i<args.length;i++) {
String str = args[i];

//creating each object differently
obj[i] = new CreateObjArr(args);
obj[i].getString();
}
}
}


The above approach is giving me error "variable obj might not have been initialized"
I know I can create array of objects like this:
CreateObjArr[] obj = new CreateObjArr[4];
But as you can see I am creating each object differently.

Could you help me out finding a way.

Best Regards,
Kaustubh Kane
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Kaush Kane:
...I know I can create array of objects like this:
CreateObjArr[] obj = new CreateObjArr[4];
But as you can see I am creating each object differently...

That line will create the array itself (containing null references). It has nothing to do with how the elements themselves are created.

Unlike class or instance variables, local variables (like "obj") are not initialized to a default value, so you need to explicitly value them before trying to use them. This would cause the error you are reporting.

But I'm really surprised that your compiler got far enough to complain about an uninitialized local variable, because this code has more serious problems. (For example, why are you trying to redefine "args"?)


"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
Kaush Kane
Ranch Hand

Joined: May 22, 2006
Posts: 37
thnks a lot.
Oh no. My actual code is different and application specific which I cannot share. hence i wrote an equivalent code and in a hurry used "args"

Thanks a lot for helping.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Creating array of objects
 
Similar Threads
arrays -- obj vs ref var to obj
Arrays
Java ---== operato
UnInitialized Strings
Interface