Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Creating array of objects  RSS feed

 
Kaush Kane
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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"?)
 
Kaush Kane
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!