Call-by-reference for primitives in Java

Java is call-by-value for primitives and offers no referencing / dereferencing operators. To emulate call by reference on primitive types you must use mutable classes that encapsulate them… a simple design pattern that does the job:


public class Mutable {
  private static Mutable instance = new Mutable();
  private Mutable() {}

  public class Integer {
    public Integer(int val) {
      this.value = val;
    }
    public int value;
  }

  public class Long {
    public Long(long val) {
      this.value = val;
    }
    public long value;
  }

  public static Integer createMutableInteger(int val) {
    return instance.new Integer(val);
  }

  public static Long createMutableLong(long val) {
    return instance.new Long(val);
  }
}

Simple, and doesn’t busy up your project will a class-per mutable primitive… as they are all packaged as inner classes :). Also the mutable design pattern can avoid the need to have to create tuple classes in order to retreive multiple data for a single call.

To use:

public int foo(String str, Mutable.Integer out1, Mutable.Integer out2) {
  ...
  out1.value = result1;
  out1.value = result2;
  ...
  return result3;
}

public void bar() {

  Mutable.Integer res1;
  Mutable.Integer res2;</code>

  int res3 = foo("test", res1, res2);</code>

  ...
}