Java Reference
In-Depth Information
There are many kinds of operations that can be performed on strings, but let's start with one you have used
already, joining two or more strings to form a new, combined string. This is often called
string concatena-
tion
.
Joining Strings
To join two
String
objects to form a new, single string you use the
+
operator, just as you have been doing
with the argument to the
println()
method in the program examples thus far. The simplest use of this is to
join two strings together:
myString = "The quick brown fox" + " jumps over the lazy dog";
This joins the two strings on the right of the assignment and stores the result in the
String
variable
myString
. The
+
operation generates a completely new
String
object that is separate from the two original
String
objects that are the operands, and a reference to this new object is stored in
myString
. Of course,
you also use the
+
operator for arithmetic addition, but if either of the operands for the
+
operator is a
String
object or literal, then the compiler interprets the operation as string concatenation and converts the operand
that is not a
String
object to a string.
Here's an example of concatenating strings referenced by
String
variables:
String date = "31st ";
String month = "December";
String lastDay = date + month; // Result is "31st December"
If a
String
variable that you use as one of the operands to
+
contains
null
, then this is automatically
converted to the string
"null"
. So if the
month
variable were to contain
null
instead of a reference to the
string “
December
”, the result of the concatenation with
date
would be the string
"31st null"
.
Note that you can also use the
+=
operator to concatenate strings. For example:
String phrase = "Too many";
phrase += " cooks spoil the broth";
After executing these statements, the variable
phrase
refers to the string
"Too many cooks spoil the
broth"
. Of course, this does not modify the string
"Too many"
. The string that is referenced by
phrase
after this statement has been executed is a completely new
String
object. This is illustrated in
Figure 4-7
.