views:

177

answers:

5

Is it possible to set a variable, if i want to have it flexible? I think an exmaple makes it easier to understand.

String hallo1;
String hallo2;

for(int i = 0; i < 2; i++) {
 hallo & i = Integer.toString(i);
}
+13  A: 

No, you cannot. There's (fortunately) no such thing as eval() in Java.

Your best bet is to grab an Array or an ArrayList. Here's an Array example:

String[] hallos = new String[2];

for (int i = 0; i < 2; i++) {
    hallos[i] = Integer.toString(i);
}
BalusC
+1 for the "fortunately". This sort of thing in scripting languages makes them very difficult to maintain. There's no way to tell where a variable is used.
Jay
A: 

No, the way to do something like this is with an array, list, or something similar. It's also more intuitive to group them together then to have many variables (that really should be related) floating around. There's no way to do this - in Java, at least. I've seen this done in scripting languages but that's a whole different thing...

froadie
An array is not the only way. You can also use a List or a Map or ...
Joachim Sauer
@Joachim Sauer - Thanks, I just realized my wording sounded limiting. I'll change that.
froadie
+4  A: 

It's technically possible with reflection, but I would advise against it unless you have a really good reason to do it. It would make your code much more difficult to debug and to read.

EDIT:
As the comments stressed:

  1. To clarify, I strongly suggest not to be tempted to use reflection. The other answers point out better ways to achieve your goal, such as an array.
  2. Reflection won't help you with local variables.
Eli Acherkan
Not local variables.
Tom Hawtin - tackline
I'm not sure why Eli was downvoted on that one. Sure, you can't do it with local variables. But it's not at all clear from the question that using local variables was a requirement. Like Eli, I'd recommend being very cautious about using reflection because it makes the code so much more difficult to read and maintain. But it can be done.
Jay
The no-local-variables restriction is just one drawback of this. In my opinion the problem with that suggestion is that questions like this ones are usually asked because someone doesn't know arrays/collections and tries to do something for which they would be perfectly suited.Suggesting reflection in such a case would only send them on a long and dangerous path that leads nowhere.
Joachim Sauer
@Joachim: I agree with you completely, that's why I was recommending _against_ reflection.
Eli Acherkan
+2  A: 

If you really have a need to have variables with names not known at compile time, you can achieve this effect by creating a structure that holds arbitrary names and values. Like, you could create a HashMap where the key is the name. Then your example above becomes something like:

  HashMap myData=new HashMap();
  for (int i=0;i<2;++i)
  {
    myData.put("hallo"+i,Integer.toString(i));
  }

Later you'd pull them out with:

  String whatever=myData.get("hallo1");

etc.

Of course you can't access values from the map as variables directly, you'd always have to do put and get to update and retrieve them, but the concept is the same.

That said, I'd be very cautious about doing this, because it makes the code difficult to maintain. If the names that you need are really coming out of the blue -- if you're writing generic code to read an arbitrary database table whose name was typed in by the user at runtime or something like that -- cool. But if you're thinking that this is a handy shortcut for something like:

  if (region.equals("1"))
    region1Total+=amount;
  else
    region2Total+=amount;

My simple answer would be DON'T!! The code is much easier to maintain if you use the IF statement and normal variables. Then anyone reading the code can look at your declarations and see what all the possible variables are. You can do text searches to find everywhere they're used. If you mis-spell a variable name, instead of magically creating a new variable you will get a clean compile-time error message. Etc.

On the other hand, if you COULD write something like

  String n=getInputFromScreen();
  String s=getAnotherInputFromScreen();
  hallo & n = s;

you would have no idea what variables exist in your program and no way to track where they are used.

Jay
A: 

You can use String array.
Something like:

 String[] hallos = new String[10];

 //when looping you can use regular (counter) loop or for each loop
 for (String s: hallos){
       //do whatever you want with each String
 }
medopal
Be careful with presenting a foreach loop here, because the question is about setting variables and assigning to `s` won't have the intended effect with this code (i.e. it won't change `hallos`).
Joachim Sauer
i know, thats why i didnt put the same body for the loop. Just teaching the OP how to use for each loop.
medopal