I want to create a new variable with each run of this while loop
the syntax of loop is

while(rs.next() && i<=num)
String str(i)=rs.getString(1);

I want that with each run the value of i should be appended with str so that with each run a new string variable is created like str1(for 1st run),str2(for 2nd run) and so on.Can anyone help me?

You can do two things.
1. Create another String but initialize it before the while loop. and then in the while loop when you are creating the new string, append the newly created string in the string created above.

2. Use the string builder class. Declare it out before the while loop. Then in the while loop simple append the newly created string, the one you are doing currently, into the string builder object. Then you can get all the appended strings from the string builder object by calling the


Method on it.

Hope it helps. :)


Also to add up, I suggest the second approach.

I want to create a new variable with each run of this while loop ... like str1(for 1st run),str2(for 2nd run) and so on

Short answer: you can't create new variables names like that at runtime. That's what arrays are for - str[1]. str[2] etc. Why do you think you need to create new variable names?

Ok now your question is more clear. I thought you wanted to append the string value.
Well yes I will agree with the post above that you can't really do that in run time. And what you are asking for isn't efficient coding. If appending the strings is what you really need then I have answered that. You may use list for storing separate strings.

But I am also confused why would you need to do something like that.


I suspect that a more appropriate approach would be to create a single variable that is an 'ArrayList<String>' before the loop, and then call '.add(String)' in the loop.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.