-3

Say for instance I want to repeat the line of code

Integer int1 = new Integer(value1);

for many variables, such as int1 to int100. I am not asking about this exact task in particular - I am asking about any such situation where the code would be identical save for replacing small details like int1 and value1 with int2, value2. Is there a way to have the JVM complete this for me?

I am not even sure what approach to take on this or what term to search for more information. The only thing I can think to try is instead of typing "int1", having a loop that changes a string containing the name and attempting to pass the string as a symbol to the JVM but this of course does not work.

JLDoucet
  • 3
  • 1
  • 4
    For this reason in Java we have Collections. I.e. Lists, Arrays, Maps etc. You can put all values in a list and all Integers in another list. This should also help : https://stackoverflow.com/questions/8631935/creating-a-variable-name-using-a-string-value – Aqeel Ashiq Feb 15 '23 at 08:00
  • In programming, if you ever find yourself wanting to create many variables of the same type, then you should immediately consider using an array, list, set, map, or other data structure that represents a collection of items. With a naming pattern like `valueX`, where `X` is replaced by incrementing numbers, then an array or list is the ideal choice. It's the same idea as how if you find yourself writing fundamentally the same code over and over, you should immediately consider using a loop or creating a method, depending on the context. – Slaw Feb 15 '23 at 08:16

1 Answers1

2

It was a little strange question and I don't know if I understood your meaning correctly or not. But in this particular case, instead of repeating the code, you can use a data structure like an array. See Oracle tutorial.

int[] numvar = new int[arr.length];
for (int i = 0; i < args.length; i++) {
    int someNumber = Integer.parseInt(args[i]);
    numvar[i] = someNumber;
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Soheil Babadi
  • 562
  • 2
  • 4
  • 15
  • 1
    What about in a case where I want 100 individually named variables (for some arbitrary reason) instead of an array? Also, thank you for not treating me like an infant. I appreciate the time you've taken to help me. – JLDoucet Feb 15 '23 at 08:25
  • @JLDoucet It's difficult to imagine a plausible scenario where you would need to do such a thing where an array/list or map (also known as a dictionary) could not be used instead, likely with a loop or some other dynamic approach to create the objects. That said, Java doesn't provide anything in the language to generate variables whose names are also generated from some kind of pattern. You could of course write a script (in another language, some IDE feature, or even another Java program) that writes your code for you. – Slaw Feb 15 '23 at 10:20