Java Reference
In-Depth Information
This construction means that
toString()
is always available for any object, and this
turns out to come in very handy for another major syntax feature that Java provides
—string concatenation.
String concatenation
Java has a language feature where we can create new strings by “adding” the charac‐
ters from one string onto the end of another. This is called
string concatenation
and
uses the operator
+
. It works by first creating a “working area” in the form of a
StringBuilder
object that contains the same sequence of characters as the original
string.
The builder object is then updated and the characters from the additional string are
added onto the end. Finally,
toString()
is called on the
StringBuilder
object
(which now contains the characters from both strings). This gives us a new string
with all the characters in it. All of this code is created automatically by
javac
when‐
ever we use the
+
operator to concatenate strings.
The concatenation process returns a completely new
String
object, as we can see in
this example:
String
s1
=
"AB"
;
String
s2
=
"CD"
;
String
s3
=
s1
;
System
.
out
.
println
(
s1
==
s3
);
// Same object?
s3
=
s1
+
s2
;
System
.
out
.
println
(
s1
==
s3
);
// Still same?
System
.
out
.
println
(
s1
);
System
.
out
.
println
(
s3
);
The concatentation example directly shows that the
+
operator is not altering (or
mutating
)
s1
in place. This is an example of a more general principle: Java's strings
are immutable. This means that once the characters that make up the string have
been chosen and the
String
object has been created, the
String
cannot be changed.
This is an important language principle in Java, so let's look at it in a little more
depth.
String Immutability
In order to “change” a string, as we saw when we discussed string concatenation, we
actually need to create an intermediate
StringBuilder
object to act as a temporary
scratch area, and then call
toString()
on it, to bake it into a new instance of
String
. Let's see how this works in code:
String
pet
=
"Cat"
;
StringBuilder
sb
=
new
StringBuilder
(
pet
);
sb
.
append
(
"amaran"
);
m
m
n
s
a