How can I pass an array by reference in Java? For instance I need to do some operations on the arrays A and B and populate the array C which should be available to the caller.
public boolean Operate(int[] A, int[] B, int[] C)
{
//Write into the empty array C by manipulating values of A and B and it should be accessible to caller
}
I read that unlike C#, pass by reference is not there in Java. In that case what is the best way to do this.
You are getting the term ‘pass by reference‘ confused with ‘pass (the reference of an object) by value‘ (which is what Java and C#, without out/ref do). In the above, if the contents of A, B or C are changed, they are changed because NO NEW OBJECT IS CREATED/CLONED/DUPLICATED when they are passed to the method. In C#, ‘ref’ and ‘out’ how one uses ‘pass by reference‘. Note that when ‘pass by reference‘ is used, assigning to a variable changes the value of the variable pass in by the caller (this is not possible in Java).
See Wiki: Evaluation Strategies.
Edit: If you really wish to follow this approach, remember that the calling convention does not dictate object mutability. Consider the following:
However, I would simply structure the code better. There is very little reason to use this approach and it introduces more side-effects and state mutations. As you can see, there is already a run-time error that the above code introduces. As others have suggested, why not simply return the more appropriate value?