Assigning variables with dynamic names in Java?

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 = 5;
}
How can I achieve this in Java?

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 code (*). Period.

 

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 &lt; 3; i++) {

    n[i] = 5;

}

 

List n = new ArrayList();

for (int i = 1; i &lt; 4; i++) {

    n.add(5);

}

 

Map n = new HashMap();

for (int i = 1; i &lt; 4; i++) {

    n.put("n" + i, 5);

}