java - Pass-by-value (StringBuilder vs String) -


this question has answer here:

i not understand why system.out.println(name) outputs sam without being affected method's concat function, while system.out.println(names) outputs sam4 result of method's append method. why stringbuilder affected , not string? normally, calling methods on reference object affects caller, not understand why string result remains unchanged. in advance

public static string speak(string name) {     name = name.concat("4");     return name; }  public static stringbuilder test(stringbuilder names) {     names = names.append("4");     return names;  }  public static void main(string[] args) {     string name = "sam";     speak(name);     system.out.println(name); //sam     stringbuilder names = new stringbuilder("sam");     test(names);     system.out.println(names); //sam4 } 

because when call speak(name);, inside speak when

name = name.concat("4"); 

it creates new object because strings immutable. when change original string creates new object,i agree returning not catching it.

so doing :

name(new) = name(original) + '4'; // should notice both names different objects. 

try

string name = "sam"; name = speak(name); 

of course think there no need explain why it's working stringbuilder unless if don't know stringbuilder mutable.


Comments