Your guess is correct. A wrapper is needed (but not Integer as it is immutable).
Some people use single element arrays for this purpose:
int[] x = { 0 };
int[] y = { 0 };
someMethod(x, y);
return x[0] + y[0];
Many will rank that technique right up there with GOTO.
Some people define a generic holder class:
public class Holder<T> {
private T _value;
private Holder(T value) { _value = value; }
public static of(T value) { return new Holder<T>(value); }
public T getValue() { return _value; }
public void setValue(T value) { _value = value; }
}
...
Holder<String> x = Holder.of("123");
Holder<String> y = Holder.of("456");
someMethod(x, y);
return x.getValue() + y.getValue();
Some define a purpose-built type:
SomeMethodResult result = someMethod(x, y);
return result.getX() + result.getY();
Some would arrange for the work to be done inside the method, avoiding the need for by-reference arguments in the first place:
return someMethod(x, y);
Each of these techniques has advantages and disadvantages:
- arrays: simple vs. ugly, relies on array having exactly one element
- holder: safe vs. verbose, boxing
- purpose-built type: safe vs. verbose, possible overkill
- change method: safe, clean vs. not always possible
Personally, I think that Java messed up on this one. I'd rather avoid by-reference arguments, but I wish Java permitted multiple return values from a method. But, truthfully, I don't trip over this one very often. I wouldn't give a kidney for this feature. :)