Assigning a Dynamic Name to a Variable in Java

Asked 2 years ago, Updated 2 years ago, 63 views

I want to assign a value on multiple variables in Java

as follows.

int n1,n2,n3;

for(int i=1;i<4;i++)
{
    n<i> = 5;
}

How can I do it in Java?

dynamic-variables java variable

2022-09-21 22:53

1 Answers

I don't think you worked on Java with the code you wrote. Dynamic variables do not exist in Java. Variables in Java must be declared (*) on the source code.

You must use List or Map to process the tasks you want. For example, like this.

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

*-The above description is slightly incorrect. If you use BCEL or ASM, you can declare variables within the byte code file. But don't use it because it's a bad way.


2022-09-21 22:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.