All arguments in Java are passed by value. When you pass a String
to a function, the value that's passed is a reference to a String object, but you can't modify that reference, and the underlying String object is immutable.
The assignment
zText += foo;
is equivalent to:
zText = new String(zText + "foo");
That is, it (locally) reassigns the parameter zText
as a new reference, which points to a new memory location, in which is a new String
that contains the original contents of zText
with "foo"
appended.
The original object is not modified, and the main()
method's local variable zText
still points to the original (empty) string.
class StringFiller {
static void fillString(String zText) {
zText += "foo";
System.out.println("Local value: " + zText);
}
public static void main(String[] args) {
String zText = "";
System.out.println("Original value: " + zText);
fillString(zText);
System.out.println("Final value: " + zText);
}
}
prints:
Original value:
Local value: foo
Final value:
If you want to modify the string, you can as noted use StringBuilder
or else some container (an array or an AtomicReference
or a custom container class) that gives you an additional level of pointer indirection. Alternatively, just return the new value and assign it:
class StringFiller2 {
static String fillString(String zText) {
zText += "foo";
System.out.println("Local value: " + zText);
return zText;
}
public static void main(String[] args) {
String zText = "";
System.out.println("Original value: " + zText);
zText = fillString(zText);
System.out.println("Final value: " + zText);
}
}
prints:
Original value:
Local value: foo
Final value: foo
This is probably the most Java-like solution in the general case -- see the Effective Java item "Favor immutability."
As noted, though, StringBuilder
will often give you better performance -- if you have a lot of appending to do, particularly inside a loop, use StringBuilder
.
But try to pass around immutable Strings
rather than mutable StringBuilders
if you can -- your code will be easier to read and more maintainable. Consider making your parameters final
, and configuring your IDE to warn you when you reassign a method parameter to a new value.