Java Reference
In-Depth Information
Strings and the Operator +
One of the most common operations performed on strings is the concatenation opera-
tion, which allows a string to be appended at the end of another string. The operator +
can be used to concatenate (or join) two strings as well as a string and a numeric value or a
character.
Next we illustrate how the operator + works with strings. Consider the following
expression:
"Sunny" + " Day"
This expression evaluates to
"Sunny Day"
Now consider the following expression:
"Amount Due = $" + 576.35
When the operator + evaluates, the numeric value 576.35 is converted to the string
"576.35" , which is then concatenated with the string:
"Amount Due = $"
Therefore, the expression "Amount Due = $" + 576.35 evaluates to
"Amount Due = $576.35"
Example 2-10 further explains how the operator + works with the String data type.
EXAMPLE 2-10
Consider the following expression:
"The sum = " + 12 + 26
This expression evaluates to
"The sum = 1226"
This is not what you might have expected. Rather than adding 12 and 26 , the values 12
and 26 are concatenated. This is because the associativity of the operator + is from left to
right, so the operator + is evaluated from left to right. The expression
"The sum = " + 12 + 26
is evaluated as follows:
"The sum = " + 12 + 26 = ("The sum = " + 12) + 26
= "The sum = 12" + 26
= "The sum = 12" + 26
= "The sum = 1226"
Now consider the following expression:
"The sum = " + (12 + 26)
 
 
Search WWH ::




Custom Search