First of all: Java does not allow for pass-by-reference. Further, out-parameters (when a function's calculations/results are placed in one or more of the variables passed to it) are not used; instead, something is return
ed from a method like so:
b = a(b);
Otherwise, in Java, you pass objects as pointers (which are incorrectly called references). Unfortunately (in your case) most types corresponding to int
(Integer
, BigInteger
, etc.) are immutable, so you cannot change the properties in the object without creating a new one. You can, however, make your own implementation:
public static class MutableInteger {
public int value;
public MutableInteger(int value) {
this.value = value;
}
}
public static void main(String[] args) {
MutableInteger b = new MutableInteger(2);
increment(b);
System.out.println(b.value);
}
public static void increment(MutableInteger mutableInteger) {
mutableInteger.value++;
}
The following will be printed to the console when this code is run:
3
At the end of the day, using the above requires a strong argument on the programmer's part.