Skip to main content

Java Uses Call By Sharing

· 3 min read

I just saw [Java: It is most certainly pass by value]. It is very shocking that I can still often see people saying "Java is call by value". I mean, I don't really get why it is even controversial. I think it is clear that "Java is call by value". Oh, actually it is more precisely "call by sharing" (Notice that it is NOT "call by reference").

Call-by-reference means a reassigned reference to a method parameter variable is visible by the caller of the method which means if a new object reference is assigned to the parameter variable in a method then caller will have the newly assigned one after execution of the method whereas call-by-sharing means the new reference is not visible by the caller. Thus the old reference will still remain after calling the method. That means if a new reference is assigned to the parameter variable, it is visible just within the method thus after execution of the method, the caller will still get the old reference so the same old object.

The people who do not understand the difference between call-by-reference and call-by-sharing do probably not know the difference between assigning a new reference to a variable and changing the state of an object the reference of which is stored in the variable. I guess, it is presumably caused by their ignorance about a reference of object and the actual object. They perhaps think a variable is an object itself or that contains an object, yet the variable does not contain an object but the reference of an object. So when we use a variable to change the state of an object or use the methods in it, we are not directly having the actual object but are using the reference of the object stored in the variable in order to access the object.

To sum up, Java uses call-by-sharing NOT call-by-reference. The difference between call-by-reference and call-by-sharing is

call-by-reference: You are able to assign a new reference to a method parameter variable in a method, and it will be visible by the caller of the method so after calling the method, the caller will get the new reference (new object).

call-by-sharing: You are able to assign a new reference to a method parameter variable in a method, BUT it will NOT be visible by the caller of the method so after calling the method, the caller will still get the same old reference which was passed as a method parameter to the method.

In both evaluation strategies, you have access to the reference so are able to change the state of the object the reference of which is stored in the parameter variable if the object is mutable. Therefore it is possible to change the values of the object member variables in the method and these changes are visible by the caller but the caller still see the same old object with a different state from the state it had before calling the method.