I'd like to assign a set of variables in java as follows:
int n1,n2,n3; for(int i=1;i<4;i++) { n<i> = 5; }
How can I achieve this in Java?
For variables, the Java naming convention is to always start with a lowercase letter and then capitalize the first letter of every subsequent word. Variables in Java are not allowed to contain white space, so variables made from compound words are to be written with a lower camel case syntax.
Summary: Dynamically accessing variable names can negatively impact the readability of your code and can cause it to run slower by preventing MATLAB from optimizing it as well as it could if you used alternate techniques. The most common alternative is to use simple and efficient indexing.
This is not how you do things in Java. There are no dynamic variables in Java. Java variables have to be declared in the source code1.
Depending on what you are trying to achieve, you should use an array, a List
or a Map
; e.g.
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); }
It is possible to use reflection to dynamically refer to variables that have been declared in the source code. However, this only works for variables that are class members (i.e. static and instance fields). It doesn't work for local variables. See @fyr's "quick and dirty" example.
However doing this kind of thing unnecessarily in Java is a bad idea. It is inefficient, the code is more complicated, and since you are relying on runtime checking it is more fragile. And this is not "variables with dynamic names". It is better described as dynamic access to variables with static names.
1 - That statement is slightly inaccurate. If you use BCEL or ASM, you can "declare" the variables in the bytecode file. But don't do it! That way lies madness!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With