Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create variables dynamically in Java? [closed]

Tags:

java

string

I need to create new variables Strings such that

String person1 = "female";
String person2 = "female";
........
........
String person60 = "male";
........
String person100 = "male";

This is what I tried

for (int i = 1; i <101; i++) {
  if (i<60) {
    String person+i = "female";
  }
  else {
    String person+i = "male";   
  }
}

Can anybody help me correct this code?

like image 673
Andrei Vasilev Avatar asked Oct 12 '13 15:10

Andrei Vasilev


People also ask

How do I create a dynamic variable 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. It is possible to use reflection to dynamically refer to variables that have been declared in the source code.

Can you dynamically create variables?

Use an Array of Variables The simplest JavaScript method to create the dynamic variables is to create an array. In JavaScript, we can define the dynamic array without defining its length and use it as Map. We can map the value with the key using an array and also access the value using a key.


2 Answers

A Map allows you to relate any key with any value. In this case, the key is the name of the variable, and the value is the value

Map<String, String> details = new HashMap<>();
for (int i = 1; i <101; i++) {
    if (i<60) {
        details.put("person" + i, "female");
    }
    else {
        details.put("person" + i, "male");
    }
}
like image 55
MeBigFatGuy Avatar answered Nov 11 '22 22:11

MeBigFatGuy


You are close. If you store the the gender of each person in an array, you can do it like this:

String[] persons = new String[100]
for (int i = 0; i < persons.length; i++) {
  if (i<60) {
    persons[i] = "female";
  }
  else {
    persons[i] = "male";   
  }
}

Alternately, if a person is more than a gender, consider making a class Person that holds a gender field, and then have an array of Persons. You would set the gender in a similar way.

like image 27
fvrghl Avatar answered Nov 11 '22 23:11

fvrghl