javapass-by-reference

How can I simulate pass by reference in Java?


I'm a complete Java noob. I know that Java treats all parameters as pass by value and there are several other threads where people explain this.

For example, in C++ I can do:

void makeAThree(int &n)
{
   n = 3;
}
int main()
{
   int myInt = 4;
   makeAThree(myInt);
   cout << myInt;
}

Which will output 3. I know that in Java, all parameters are passed by value and thus you can not manipulate the parameter passed in. Is there a standard way to simulate pass by reference in Java? Is there no way to call a function that manipulates a variable passed in? It's tough for me to wrap my head around the idea of there being no way to do this.


Solution

  • The primary way you can simulate passing a reference is to pass a container that holds the value.

    static void makeAThree(Reference<Integer> ref)
    {
       ref.set(3);
    }
    
    public static void main(String[] args)
    {
      Reference<Integer> myInt = new Reference<>(4);
      makeAThree(myInt);
      System.out.println(myInt.get());
    }
    

    Since in Java, it is references to objects that are passed by value (the object itself is never passed at all), setting ref to 3 in makeAThree changes the same object referred to by myInt in main().

    Disclaimer: Reference isn't a class you can just use with out-of-the-box Java. I'm using it here as a placeholder for any other object type. Here's a very simple implementation:

    public class Reference<T> {
        private T referent;
    
        public Reference(T initialValue) {
           referent = initialValue;
        }
    
        public void set(T newVal) {
           referent = newVal;
        }
    
        public T get() {
           return referent;
        }
    }
    

    Edit

    That's not to say it's great practice to modify the arguments to your method. Often this would be considered a side-effect. Usually it is best practice to limit the outputs of your method to the return value and this (if the method is an instance method). Modifying an argument is a very "C" way of designing a method and doesn't map well to object-oriented programming.