0

So say I have a string like "ABC", is there any possible way for me to pull out these characters individually and assign values to those as if they were a variable name?

For instances

String temp = "ABC";    //temp.charAt(1) being 'B' and assigning 5 to 
int temp.charAt(1) = 5; //the variable name 'B'

Obviously that syntax is no where near correct, I'm just using it to explain what I'm trying to achieve.

Is this even a possible thought? Sorry for the trivial question, I'm fairly new to java.

ajkey94
  • 411
  • 2
  • 10
  • 19
  • Or even: http://stackoverflow.com/questions/6729605/assigning-variables-with-dynamic-names-in-java – Sotirios Delimanolis Jan 28 '14 at 18:42
  • 4
    Nope, and there's no need for that either. A lot of beginners hope for something like that though :) – Kayaman Jan 28 '14 at 18:42
  • What are you trying to achieve by doing this exactly? – crush Jan 28 '14 at 18:44
  • Variable names are not nearly as important as all that, and almost don't even exist in compiled code. The key, has been discussed much before, is being able to get a reference to an object of interest. For this you can use variables, arrays, or collections such as ArrayLists, or often a Map such as a `HashMap`. – Hovercraft Full Of Eels Jan 28 '14 at 18:48
  • https://www.google.com/search?q=Is+it+possible+to+create+variable+names+from+characters+in+a+string – aliteralmind Jan 28 '14 at 18:55
  • This gets asked about once every 2 weeks. In most languages (including Java) the answer is NO. You can achieve a few hints of the function using Java "reflections", but that's about it. Arrays/Lists and "Maps" (hashtables) give you some of the functionality of the concept, but not with the sort of syntax you might envision. – Hot Licks Jan 28 '14 at 19:10
  • @Kayaman - I wouldn't say that there's "no need" for such a capability. The few languages that have it are capable of some pretty interesting/powerful things as a result. – Hot Licks Jan 28 '14 at 19:12
  • @HotLicks Well, you could emulate that with maps, and I don't see anything powerful coming out of that. I was just referring to how people new to programming see it as very logical that you could use variables for anything, including creating new variables. – Kayaman Jan 29 '14 at 07:23
  • @Kayaman - APL and REXX had that capability, and you could do some pretty useful things with the capability in those languages. It's been so long that I can't remember any good examples, however. – Hot Licks Jan 29 '14 at 12:52

1 Answers1

5

Use a data structure instead, like this:

Map<Character, Integer> vars = new HashMap<Character, Integer>();
String temp = "ABC";
vars.put(temp.charAt(1), 5); // B = 5
System.out.println(vars.get('B')); // 5
System.out.println(vars.get(temp.charAt(1))); // 5