Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Assign values to variables dynamically

Status
Not open for further replies.

mfalomir

Technical User
Feb 6, 2003
78
MX
Im new to Java, Im just beginning with it because I was required to do it at work :) So long has been a fun ride, I have a question though, is it possible to assign values to variables dynamically ? For example if I have some labels

Label name1;
Label name2;
.
.
Label nameN;

Set their values with a for loop ?

I was hoping that I could do it as with Flash (im an actionscripter)

for ( var i=1; i <= N; i++)
{
this["name" + i].setText("Bla bla bla");
}

Thanks in advanced!
 
No, you cannot do that - its a compiled language, not an interpreted scripting language.

The closest you can get is to have an array :

Code:
Label[] labelsArray = new Label[3];
for (int i = 0; i < labelsArray.length; i++) {
  labelsArray[i] = new Label();
  labelsArray[i].setText("Bla " +i);
  
}




--------------------------------------------------
Free Database Connection Pooling Software
 
Well, Java is not an scripting language, so the inmediate answer is that you cannot build variable names at runtime.

I'd suggest to store all those variables in an array, so you can access them with a loop.

Another way is using reflection to access the variables but it's a bit tricky if you're just beginning. Anyway, you can take a look at
Cheers,

Dian
 
Hehe, Thanks for your answers, very appreciated :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top