Java Reference
In-Depth Information
W
ORKING WITH
S
TRINGS
String
s can easily be concatenated using the + operator:
String localText = ("Some text ");
localText += "/ Some other text";
After execution of the second statement,
localText
would point to a (new)
String
containing “Some text / Some other text.”
The + operator will automatically convert any data type into a
String
if necessary.
String localText = ("Some text ");
int x = 4;
localText += "/ "
localText += x;
After execution of the second statement,
localText
would point to a (new)
String
containing “Some text / 4.”
As a COBOL programmer, one would think that to add a number to a
String
might be considered a nonsensical operation, yielding unpredictable results. What
would happen in COBOL if you said the following:
ADD 4 TO "Some Text".
Some sort of compiler error, you hope! But in Java, this type of statement is
perfectly legal. The numeric item automatically gets converted into a
String
.
Java accomplishes this by assigning special processing to the + operator in some
cases, such as when the destination is a
String
variable. In this case, the + operator
becomes a
concatenate
operator. If any of the source operands are not
String
s, they
will automatically be converted into
String
s by the compiler, and then concate-
nated. In the example, the value 4 was originally created as an integer, and then it
was converted into the character
String 4
. This
String
was then added to the text
in
localString
, creating a new
String
object.