I'm writing some code for an exercise of a book I'm currently working through on my own and I stumbled over a problem while rewriting some working code into something more readable.
The Problem
I have method A which calls method B, passing it an int value (e.g. int value = 5). I want B to look at the int value and if it is >0, decrement it by 1 (e.g.: int value = 4) and return a boolean true
if int value was > 0. However I also want the change of the int value in B to affect the original int value in A. Since this does not work in java with primitives, I thought my problem would be solved here if I passed an Integer
.
Example Code
public class Test {
private static boolean isRemainder0(Integer remainder) {
boolean is0 = true;
if (remainder.intValue() > 0) {
remainder = remainder.intValue() - 1;
is0 = false;
}
return is0;
}
public static void main(String[] args) {
Integer remainder = 5;
System.out.println(remainder);
System.out.println(isRemainder0(remainder));
System.out.println(remainder);
}
}
What I would want is for this to return 5 - false - 4. What this does return:
5
false
5
Why this does not work
Apparently if you pass a variable var1 containing an object reference, you do not pass var1 but a copy var2 == var1 of it to the new method. Therefore changes to var2 in the new method do not affect var1.
The question
How do I find a way around it?
Solutions that I want to avoid
- Using a static variable for
remainder
- Writing a custom object containing the boolean and the changed int value of "remainder"
- Solutions requiring me to instantiate "Test"
- Solutions requiring me to lose the return of isRemainder0
1) I want to avoid because I'm currently trying to avoid using static variables whenever possible. 2) I want to avoid because it seems to me like bad coding.