Package Virtual;class stan{string mm = "Hello";} Class Virtual {public static void main (string[] args) {Stan s=new stan (); System.out.println (S.MM); Change (s); System.out.println (S.MM);} public static void Change (Stan s) {s.mm= "say";//actually changed the address of the MM point to the string, from the address that points to hello to the address of say, hello still exists, just does not point to it}}
MM just started pointing to hello that piece of memory, when passed in the change function, the object is a reference to the original object, you can directly point to the original object mm address, If you change s.mm to say, because the string type is immutable, you can only reallocate a memory space for say, and the value of mm points to say memory, so the output will change,
In fact, changed the string object mm point to the address, from the address to hello to the address of the say, Hello is still there, just do not point to it
Let's look at another example.
Package Virtual;class stan{string mm = "Hello";} Class Virtual {public static void main (string[] args) {String s= "123"; System.out.println (s); Change (s); System.out.println (s);} public static void Change (String s) {s= "Say";}}
At this point S has not been changed, this is why? Because the function was passed in, a copy of the string object was copied, which pointed to the memory space of say, but the original string object pointed to 123 of the memory space, so s did not change. The string type can be thought of as a pass-through, that is, to create another string object independent of the original object
Package Virtual;class stan{int temp=10;} Class Virtual {public static void main (string[] args) {Stan s=new stan (); System.out.println (s.temp); Change (s); System.out.println (s);} public static void Change (Stan s) {s.temp=30;}}
This is the same as Example 1, is also a reference to the passing object, that is, the address, and temp is an int, can be changed, so directly change the heap area of temp is 30
Not to be continued
String type and object passing value