This is not how you do it in Java. There are no dynamic variables in Java. Java variables must be declared in source code (*). Period.
Depending on what you are trying to achieve, you should use an array, List or Map ; eg.
int n[] = new int[3]; for (int i = 0; i < 3; i++) { n[i] = 5; } List<Integer> n = new ArrayList<Integer>(); for (int i = 1; i < 4; i++) { n.add(5); } Map<String, Integer> n = new HashMap<String, Integer>(); for (int i = 1; i < 4; i++) { n.put("n" + i, 5); }
You can use reflection to dynamically access variables that have been declared in source code. However, this only works for variables that are members of a class (i.e., Static fields and instances). It does not work for local variables. See the @fyr quick and dirty example.
However, doing such things without the need for Java is a bad idea. This is inefficient, the code is more complex, and since you rely on runtime checking, it is more fragile.
And these are not "dynamic name variables". It better describes dynamic access to variables with static names.
* - This statement is a little inaccurate. If you use BCEL or ASM, you can "declare" variables in the bytecode file. But do not do it! So madness!
Stephen C Jul 18 '11 at 7:10 2011-07-18 07:10
source share