I have the following code which has
a mutable Person class, String and a method to modify the instances of String and Person
class Person{
int a = 8
In modifyObject
, When you assign to str
, you're not mutating str
, you're setting it so that it points to a different object. Since it's passed by value, the str
pointer local to your modifyObject
method is a copy of the s
pointer in main
, so when you change the former, it does not affect le later.
On the other hand, when it comes to p
, the one in modifyObject
is still a copy of the one in main
, but both pointers refer to the very same object in memory, hence if you call a method on it from modifyObject
, you're actually mutating the thing pointed to by p
.