Pass-by-value (StringBuilder vs String)
Because String
is immutable and hence String#concat
does not modify the original String instance, it only returns a new String
while the original is left unmodified, while StringBuilder
is mutable and the change is reflected in the StringBuilder
instance passed as parameter.
Looking at the Javadoc for String
, one will read that
[...] String objects are immutable [...].
This means concat(String)
does not change the String
itself, but constructs a new String
.
StringBuilder
s, on the other hand, are mutable. By calling append(CharSequence)
, the object itself is mutated.
Because when you call speak(name);
, inside speak when you do
name = name.concat("4");
it creates a new object because String
s are immutable. When you change the original string it creates a new object,I agree that you are returning it but you are not catching it.
So essentially what you are doing is :
name(new) = name(original) + '4'; // but you should notice that both the names are different objects.
try
String name = "Sam";
name = speak(name);
Of course now I think there is no need to explain why it's working with StringBuilder
unless if you don't know that StringBuilder
is mutable.