Code
class Test {
public static void main(String args[]) {
StringBuffer a = new StringBuffer("A");
StringBuffer b = new StringBuffer("B");
modify(a, b);
System.out.println(a + " " + b);
}
public static void modify(StringBuffer a, StringBuffer b) {
a.append(b);
a = b;
System.out.println(a + " " + b);
}
}
I understand the print statement in function modify and I also know StringBuffer class modifies String inplace therefore a.append(b) makes String refer to “AB”.
My question is how can String a be changed to “AB” outside the function modify but statement a=b has no impact outside function modify. Basically, when is variable passed by value, when by reference?
Here’s a simple picture:
In
main, bothaandbare references that point to separate StringBuffer instances. Whenmaincallsmodify, it passes copies of the referencesaandb(pass by value).modifycan change the contents of the StringBuffer instances, but if it changes the values ofaandb, it operates only on its own local copies and does not affect whatmain‘saandbpoint to.The basic answer is that everything is passed by value, but when passing objects it’s the reference that is passed (by value), not the object itself.