The concatenation of chars to form a string gives different results

char, concatenation, java, string

Solution

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

Problem

Why, when I use the operation below to sum chars, does it return numbers instead of chars? Shouldn't it give the same result? ``` ret += ... ; // returns numbers ret = ret + ...; // returns chars ``` The code below duplicates the chars: doubleChar("The") → "TThhee" ``` public String doubleChar(String str) { String ret = ""; for(int i = 0; i < str.length(); i++) { ret = ret + str.charAt(i) + str.charAt(i); // it concatenates the letters correctly //ret += str.charAt(i) + str.charAt(i); // it concatenates numbers } return ret; } ```

Original source