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.
The primary way you can simulate passing a reference is to pass a container that holds the value.
Since in Java, it is references to objects that are passed by value (the object itself is never passed at all), setting
refto3inmakeAThreechanges the same object referred to bymyIntinmain().Disclaimer:
Referenceisn’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: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.