The following statements,
String string = "string";
string = string +((char)65) + 5;
System.out.println(string);
Produce the output stringA5
.
The following however,
String string = "string";
string += ((char)65) + 5;
System.out.println(string);
Produce string70
.
Where is the difference?
Case 1
everything is treated as String but in second case
Sequence of operation performed:
string +((char)65 = stringA
stringA + 5 = stringA5
Case 2
first right hand side is calculated means first operation will be like
((char)65) + 5
, So result of((char)65) + 5 is 70
and after that += operation.Sequence of operation performed:
(char)65 + 5 = 70
string + 70 = string70
Lets see 1 more example
Output string70A
Reason Same first right hand side is calculated and sequesce of opertion performed is
(char)65 + 5 = 70
70 + "A" = 70A
string + 70A = string70A
This means "Set string to the concatenation of
string
,((char)65)
, and5
." This gets evaluated from left-to-right (so firststring + ((char)65)
, then that+5
, and concatenation of a string and an integer converts that integer to a string.This means "Calculate the result of
((char)65)+5
and add it to string" - the entire right-hand side is evaluated before adding the result to the string. Since achar
is really just a 16-bit integer, it adds them together as integers - giving 70 - and then it appends that tostring
.When you write:
It is like writing:
Which is like appending
string
toA
(The char representation of the decimal 65) and5
.In the latter, you're first calculating the right hand, and then adding the result to
string
, it's like writing:You see this behavior as a result of the combination of operator precedence and string conversion.
JLS 15.18.1 states:
Therefore the right hand operands in your first expression are implicitly converted to string:
string = string + ((char)65) + 5;
For the second expression however
string += ((char)65) + 5;
the+=
compound assignment operator has to be considered along with+
. Since+=
is weaker than+
, the+
operator is evaluated first. There we have achar
and an int which results in a binary numeric promotion toint
. Only then+=
is evaluated, but at this time the result of the expression involving the+
operator has already been evaluated.It is the same case as the example:
produces abc105 (add as String)
and
produces 15 (add as Number)
The
String
included in the (first place of the) operation forces all the elements to be treated asStrings
while executing the operation. In your case with+=
however, the operation is executed first in the right part (treating the elements asint
) because of the operator precedence and then is concatenated with theString
.