4

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); } 
4
  • 1
    Sorry the example does not make it any clearer Commented Feb 9, 2010 at 14:08
  • 4
    This is a common request of beginners. Usually the correct solution is to use an array, a List, a Set or a Map. Commented Feb 9, 2010 at 14:10
  • I don't want to make a String-Array. The String is only an example. I have a GridLayout(3,3) and in every field a GridLayout(3,3) again. now I want to make the 81 Labels like: field_A1_A1, field_A1_A2... etc... Maybe now you understand my problem. Commented Feb 10, 2010 at 6:48
  • In that case, you can use for loops: for (int x = 0; x < 3; x++) { for (int y = 0; y < 3; y++) { String currentName = "field_A" + x + "_A" + y; currentGridLayout.addLayoutComponent(currentName, new Label(currentName)); } } will create one 3x3 grid with 9 Label s, and you can use the same principle for the outer 3x3 grid. Commented Feb 10, 2010 at 7:17

5 Answers 5

13

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); } 
Sign up to request clarification or add additional context in comments.

1 Comment

+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.
4

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.

3 Comments

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.
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: I agree with you completely, that's why I was recommending against reflection.
2

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.

Comments

0

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 } 

2 Comments

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).
i know, thats why i didnt put the same body for the loop. Just teaching the OP how to use for each loop.
0

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...

1 Comment

@Joachim Sauer - Thanks, I just realized my wording sounded limiting. I'll change that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.