1

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 ?

4
  • 1
    There's no dynamic variable in Java. Try using a HashMap or an ArrayList to hold your variables. Commented Jul 7, 2012 at 5:14
  • is there no way to do it like that :S ? Commented Jul 7, 2012 at 5:18
  • Why do you need such thing? However, you might do it via Reflection, though I am not sure. Commented Jul 7, 2012 at 5:20
  • I want it like that because there is another issue with java i didn't find any way of declaring associative arrays ... so i am bond declaring a variable ! Commented Jul 7, 2012 at 5:25

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

-1

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");

Comments

-2

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!

3 Comments

Oh. You can't do that in Java.
that sounds disturbing for a php developer :S
Sorry! It's a strongly-typed language, not a dynamic language.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.