First look at the Java code as follows:
Import Java.util.Scanner;
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); By invoking the Append method to modify the contents of the heap memory that the object points to before the reference does not change, it is possible to modify the contents of the original StringBuffer object SB's storage.
object = SB1;
}
}
Note: Aside from the eight basic types, the rest of the types in Java are reference types, including string and reference type, as well as references.
I thought, since the passing is a reference, then the string object original to the method Modifya processing, original stored value should be changed to "value"
The same StringBuffer object SB's value should also be changed to "changed value", but the result is not, the output is "original value", and then I wonder if they passed the reference
Original: The Modifya (String B) method, when invoked, original passed to the method, which creates a new String object B that also refers to the block that the original object points to
Heap memory. And I used the statement in the Modifya method: b = "changed value"; The statement did not reach the purpose of changing the original object, and he pressed the reference address of the B object to point to "changed value".
The heap memory in which this object resides. So the original object still points to the original heap memory, of course, his output is unchanged, the same problem exists for StringBuffer object sb.
As you can see, the reason for not reaching the desired result is to use the "=" assignment operator, which modifies the reference address of the replica object (the intermediate object created by the method itself, such as B by the Modifya method).
So that he points to different heap memory (which has no effect on the original object content), and does not actually modify the exception caused by the specific values in the heap memory that he points to.
So the annotated statement in the Modifyobject method can achieve the purpose of modifying the original content.