It is important for me to distinguish between a variable and an object.
Consider the code:
String str = ""; FuntionString(str);
str is a variable. First, the value of this variable is a string reference. Let's say that this link is number 246. Line 246 can be resolved to a value; this value is an empty character array.
Then we pass the value of this variable to FuntionString . We do not pass a reference to the str variable, we just pass the number 246. This is a copy of this link or number.
Inside this function, it has a completely different variable, which is also called str . The fact that the identifier is the same does not change the fact that it is another variable that simply has the same value.
When you change the str variable inside a FuntionString , you do not change the str variable from Main . After the body of the FuntionString ends, the str from Main is still held on reference 246, as before, and the variable str inside the FuntionString is set to some new link, letβs say 3, a newline with the value "updated value" . This variable change is not reflected in Main .
In the case of FunctionSB the method implementation does not actually change the sb variable . Instead of modifying a variable, it mutates the object referenced by the variable. In this case, sb points to an object in some place, say 39. sb in the main method and in this other method are two different variables with a copy of the same link. The method does not change the sb variable; instead, it changes the sb object at location 39. The two sb objects still have the same value; they do not change, but both of them point to the same object that has changed. Thus, a mutation performed using the method can be observed from Main .
If, from the definition of FuntionString you changed the string object that both variables pointed to, instead of changing the variable itself, then the change will be "observable" from the caller. Of course, this is not possible because strings are immutable. A method cannot mutate an object so that the caller can observe.