Shoaib Ahmed
Shoaib Ahmed

Reputation: 781

Variable declaration with its name containing value from loop

i am php developer just started at java i want to declare dynamic variables inside a loop and for that i have to append the loop value to varaible name this is what i want .

I would like to make  statement like this 

for (i=1; i<6; i++)
{
String new_variable_ + i;
}

the above code does not work in java how to do it ?

Upvotes: 1

Views: 406

Answers (4)

Shoaib
Shoaib

Reputation: 90

what you are trying to do is not possible in java ... this language is not that lose like php..its a type strict language

Upvotes: 2

Matt
Matt

Reputation: 11805

Variable declarations are declared to be static identifiers and cannot contain any computed values in java (and i venture to say this would be true in any statically typed language).

You say you can't find an associative array. Have you seen the java.util.Map interface (and it's implementations)? It is by definition an associative array:

Wikipedia: In computer science, an associative array, map, or dictionary is an abstract data type composed of a collection of (key,value) pairs, such that each possible key appears at most once in the collection.

Upvotes: 2

azgolfer
azgolfer

Reputation: 15137

Like I said in the comment, there's no dynamic variable in Java. At best you can do this:

HashMap variableMap = new HashMap<String,String>();

for (int i = 1; i < 6; i++) {
   variableMap.put("new_variable_" + i, "some variable value");
}

Then to access them, you do:

String value = variableMap.get("new_variable_2");

Or to update it, you do:

variableMap.put("new_variable_2", "new value");

Upvotes: -1

jwismar
jwismar

Reputation: 12258

If you just want to use a string version of i within the loop, you need:

for (int i=1; i<6; i++)
{
  String new_variable_ = "" + i;
  //use new_variable here.
}

If you're looking for something different, I'll need some more details. Good luck!

Upvotes: -2

Related Questions