3

I have the following instantiated variable

 public static int r1 = 10;

I have several of these variables r1 - r4, I want to write a method that will be able to take the variable r1 as a parameter of the method and increment it.

Pseudo code would look like :

r1 = r1 + 1;

My question is how can I take the variable as a parameter of one method instead of writing 4 different methods to accomplish this?

Samuel Kok
  • 585
  • 8
  • 16
Ian-Fogelman
  • 1,595
  • 1
  • 9
  • 15
  • `instead of writing 4 different methods to accomplish this` ... where did four methods come into the question? – Tim Biegeleisen Oct 06 '16 at 01:20
  • Why not simply use `YourClassName.r1` inside method ? You don't need a parameter to pass on `public static` variable. –  Oct 06 '16 at 01:24

1 Answers1

4

You can't, because Java does not let you pass variables of primitive types by reference.

You can put your variables into an array, and pass an array and an index:

public static int[] r = new int[4];
...
public static void modify(int[] array, int pos) {
    array[pos]++;
}
...
modify(MyClass.r, 1); // instead of modify(MyClass.r1);

Alternative approach is to return the modified value to callers, and let them assign it back:

public static int modify(int orig) {
    return orig+1;
}
...
MyClass.r1 = modify(MyClass.r1);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523