Rohan Deshmkh wrote:why does the following program print s=aaa sb=bbbaaabbb. It will print s=aaa because Strings are immutable and whatever changes we do to str in TestRefs method will not be reflected back in the main.
It's true that
String is immutable, but that's not why main() doesn't see the changes. The reason is that
Java passes only by value. Primitives are passed by value and references are passed by value. This means that when you change the value of a parameter inside a method, the caller doesn't see the change, because the method parameter's copy of that variable is completely separate from the caller's copy.
Note that both the caller's variable and the method parameter point to the same
object though. The object doesn't get copied, just the reference.