This is not possible. There are no dynamic variables in Java. Java variables need to be declared in the source code.
The closest result you can get and using ArrayList
, String[]
or Map
.
How to:
List<String> nomes = new ArrayList();
for(int i = 0; i < 4; i++){
nomes.add(null);
}
or:
int tamanho = 4;
String[] nomes= new String[tamanho];
for(int i = 0; i < tamanho; i++){
nomes[i] = null;
}
or:
Map<String, String> nomes = new HashMap<String, String>();
for (int i = 1; i < 4; i++) {
details.put("nome" + i, null);
}
You can use reflection to dynamically reference variables that have been declared in the source code. However, this only works for variables that are class members (that is, static and instance fields). It does not work for local variables.
However, doing this kind of thing unnecessarily in Java is a bad idea. It is inefficient, the code is more complicated, and as you are relying on run-time verification, it is more fragile.
And this is not "variables with dynamic names". It is best described dynamic access to variables with static names.