The result of the following expression
ret + str.charAt(i) + str.charAt(i);
is the result of String concatenation. The Java language specification states
The result of string concatenation is a reference to a String object
that is the concatenation of the two operand strings. The characters
of the left-hand operand precede the characters of the right-hand
operand in the newly created string.
The result of
str.charAt(i) + str.charAt(i);
is the result of the additive operator applied to two numeric types. The Java language specification states
The binary + operator performs addition when applied to two operands
of numeric type, producing the sum of the operands.
[…]
The type of an additive expression on numeric operands is the promoted
type of its operands.
In which case
str.charAt(i) + str.charAt(i);
becomes an int
holding the sum of the two char
values. That is then concatenated to ret
.
You might also want to know this about the compound assignment expression +=
A compound assignment expression of the form
E1 op= E2
is equivalent
toE1 = (T) ((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.
In other words
ret += str.charAt(i) + str.charAt(i);
is equivalent to
ret = (String) ((ret) + (str.charAt(i) + str.charAt(i)));
| ^ integer addition
|
^ string concatenation