0

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.

4
  • 1
    And why you want to do that? Commented Sep 17, 2013 at 18:08
  • 3
    No, you cannot dynamically name variables in Java. Commented Sep 17, 2013 at 18:08
  • Why would you not want to use an array for this? Commented 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. Commented Sep 17, 2013 at 19:26

3 Answers 3

1

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.

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

Comments

0

This is certainly not possible because Java is statically-typed. Variables must be available at compile time, but a loop executes during run time.

Comments

0

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}

Comments

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.