Concatenation of Strings and characters

You see this behavior as a result of the combination of operator precedence and string conversion.

JLS 15.18.1 states:

If only one operand expression is of type String, then string conversion (ยง5.1.11) is performed on the other operand to produce a string at run time.

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 a char and an int which results in a binary numeric promotion to int. Only then += is evaluated, but at this time the result of the expression involving the + operator has already been evaluated.

Leave a Comment