0

Possible Duplicate:
Dynamic variable names Java

if i have an

int i =5;

how to make a new variable, which will have a value of the previous integer build into it's name?

example:

String string**i**;

so that, in the ent, my String variable will be named 

string**5**
Community
  • 1
  • 1

2 Answers2

2

You don't. You use an array:

String[] strings = new string[10];
strings[5] = "foo";
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
0

The simple answer is that you can't / shouldn't try to do that kind of stuff in Java. Java variable names must be known at compile time. Period.


And in this particular case, it seems like it would be a pointless exercise anyway. Consider this:

String buildstring_<buildNumber> = ...

How are you going to use this hypothetical variable?

if (buildstring_<buildNumber>.equals(...)) {
    ....
}

But you could have achieved the same thing like this:

String buildstring_current = ...

if (buildstring_current.equals(...)) {
    ....
}

OK, so suppose there are lots of these build strings ...

String buildstring_1 = ...
String buildstring_2 = ...
String buildstring_3 = ...

if (buildstring_<buildNumber>.equals(...)) {
    ....
}

Fine ... but what happens when <buildNumber> is one greater than the last buildstring_? declaration? Compilation error or runtime error!!!

No. The sensible way to do this in Java is to use an array or a Map ... or possibly something read from a properties file.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216