See comments
StringBuffer sb = new StringBuffer("hello"); // sb holds reference
System.out.println("String before append: "+ sb.toString()); // you print the value
addString(sb); // you use the reference to append to the StringBuffer
System.out.println("Sting after append "+ sb.toString()); // you print the value
String s = "hello"; // s holds a refernece
System.out.println("String before append: "+ s); // you print its value
addString(s); // // the word variable would hold a new reference inside the method
System.out.println("Sting after append "+ s); // you print its value
In here
public static void addString(String word){
word+=" world!";
}
The original value of the reference passed to word
changes when you reassign it with
word+=" world!";
It goes something like this
String word = [copy of value of the argument's reference];
word = word.toString() /* toString() is unnecessary, but just to make the point */ + " world";
where the result of String concatenation is a new String object and therefore a new reference.
In the following
public static void addString(StringBuffer word){
word.append(" world!");
}
you access the object referenced by word
, call a method on that object which internally modifies a char[]
. So you've changed the value of the object, not the value of the reference. Changing the reference would look like
public static void addString(StringBuffer word){
word = new StringBuffer("Answer to the Ultimate Question of Life, the Universe, and Everything: ");
word.append("42");
}
The append
is performed on a new StringBuffer
object, not the one you passed as an argument, proof that the objects are passed by value.