The java code is as follows:
Import java. util. collections;
Import org. junit. Test;
Public class TestCoreJava {
@ Test
Public void testString (){
String original = "original Value ";
ModifyA (original );
System. out. println (original );
StringBuffer sb = new StringBuffer ();
Sb. append (original );
ModifyObject (sb );
System. out. println (sb. toString ());
}
Public void modifyA (String B ){
B = "changed value ";
}
Public void modifyObject (StringBuffer object ){
String B = "changed value ";
StringBuffer sb1 = new StringBuffer ();
Sb1.append (B );
// Object. append (B); call the append method to modify the content in the heap memory that the object points to before the reference to is changed, it can be used to modify the storage content of the original StringBuffer object sb.
Object = sb1;
}
}
Note: apart from the eight basic types, all the other types in java are reference types, including the String type and the passed type.
I thought that since references are passed, after the String object original is handed over to the modifyA method for processing, the value stored in original should be changed to "changed value"
Similarly, the sb stored value of the StringBuffer object should be changed to a "changed value", but the result is not. The output is "Original Value". Then I doubt whether they pass a reference.
Originally: When the modifyA (String B) method is called, original is passed to this method, which creates a new String object B, it also references the block pointed to by the original object
Heap memory. In the modifyA method, I use the statement B = "changed value". This statement cannot be used to change the original object, he changed the reference address of object B to "changed value"
Heap memory of this object. Therefore, the original object still points to the original heap memory. Of course, its output results remain unchanged. The same problem also exists for the StringBuffer object sb.
Therefore, we can see that the reason for not reaching the expected result is that the "=" assignment operator is used to modify the copy object (the intermediate object created by the called method itself, such as B created by the modifyA method) reference address,
This causes him to point to different heap memory (which has no impact on the content of the original object), without the actual modification of the specific value in the heap memory he points.
Therefore, the commented statement in the modifyObject method can modify the original content.