The concatenation of chars to form a string gives different results

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
to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1
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

Leave a Comment