Search code examples
javapass-by-reference

How to do the equivalent of pass by reference for primitives in Java


This Java code:

public class XYZ {   
    public static void main(){  
        int toyNumber = 5;   
        XYZ temp = new XYZ();  
        temp.play(toyNumber);  
        System.out.println("Toy number in main " + toyNumber);  
    }

    void play(int toyNumber){  
        System.out.println("Toy number in play " + toyNumber);   
        toyNumber++;  
        System.out.println("Toy number in play after increement " + toyNumber);   
    }   
}  

will output this:

 
Toy number in play 5  
Toy number in play after increement 6  
Toy number in main 5  

In C++ I can pass the toyNumber variable as pass by reference to avoid shadowing i.e. creating a copy of the same variable as below:

void main(){  
    int toyNumber = 5;  
    play(toyNumber);  
    cout << "Toy number in main " << toyNumber << endl;  
}

void play(int &toyNumber){  
    cout << "Toy number in play " << toyNumber << endl;   
    toyNumber++;  
    cout << "Toy number in play after increement " << toyNumber << endl;   
} 

and the C++ output will be this:

Toy number in play 5  
Toy number in play after increement 6  
Toy number in main 6  

My question is - What's the equivalent code in Java to get the same output as the C++ code, given that Java is pass by value rather than pass by reference?


Solution

  • You have several choices. The one that makes the most sense really depends on what you're trying to do.

    Choice 1: make toyNumber a public member variable in a class

    class MyToy {
      public int toyNumber;
    }
    

    then pass a reference to a MyToy to your method.

    void play(MyToy toy){  
        System.out.println("Toy number in play " + toy.toyNumber);   
        toy.toyNumber++;  
        System.out.println("Toy number in play after increement " + toy.toyNumber);   
    }
    

    Choice 2: return the value instead of pass by reference

    int play(int toyNumber){  
        System.out.println("Toy number in play " + toyNumber);   
        toyNumber++;  
        System.out.println("Toy number in play after increement " + toyNumber);   
        return toyNumber
    }
    

    This choice would require a small change to the callsite in main so that it reads, toyNumber = temp.play(toyNumber);.

    Choice 3: make it a class or static variable

    If the two functions are methods on the same class or class instance, you could convert toyNumber into a class member variable.

    Choice 4: Create a single element array of type int and pass that

    This is considered a hack, but is sometimes employed to return values from inline class invocations.

    void play(int [] toyNumber){  
        System.out.println("Toy number in play " + toyNumber[0]);   
        toyNumber[0]++;  
        System.out.println("Toy number in play after increement " + toyNumber[0]);   
    }