I was wondering if one could declare a variable like "vx" in a loop and have it that every time it loops, the value of x changes. Such that when a loop runs through 5 times that the variables would be named v1, v2, v3, v4, v5.
-
1And why you want to do that?Rohit Jain– Rohit Jain2013-09-17 18:08:14 +00:00Commented Sep 17, 2013 at 18:08
-
3No, you cannot dynamically name variables in Java.Sotirios Delimanolis– Sotirios Delimanolis2013-09-17 18:08:29 +00:00Commented Sep 17, 2013 at 18:08
-
Why would you not want to use an array for this?Louis Wasserman– Louis Wasserman2013-09-17 18:11:12 +00:00Commented Sep 17, 2013 at 18:11
-
My main reason was because I was thinking that in a certain situation I needed to use an array in an array but I realized that I could simply just use a two-dimensional array. So really my reason for asking was out of simple curiosity.JoshSchellenberger– JoshSchellenberger2013-09-17 19:26:43 +00:00Commented Sep 17, 2013 at 19:26
Add a comment
|
3 Answers
Basically, You can't declare variables with different variable names in a loop for Java being a statically typed language.
There is no point of declaring(initializing) variables inside a loop with different names. After all, variables get out of scope and destroyed (garbage collection) if its scope is just inside the loop.
If you want to initialize class variable, you can try Reflection API but it should be avoided for many reasons.
Comments
You can't dynamically named variables in java. But you can do some thing as follows
List<String> dataList=new ArrayList<>(Arrays.asList("a","b"));
Map<String,String> map=new HashMap<>();
String preFix="var";
char postFix='1';
for(String i:dataList){
map.put(preFix+postFix,i);
postFix++;
}
System.out.println(map);
Out put:
{var1=a, var2=b}