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;
}
In your first example, you are explicitly adding a String as the first term. That forces the second and third term to also be promoted to String(s). In the second case, you are adding two characters (which are then appended to the String) - it does not promote to a String until the assignment. You could have been explicit, by using Character.toString() or String.valueOf() like so
From the Java specification:
So the
+=
operator has a built-in cast to the destination type.In contrast, the clause for simple assignment says:
Here,
is treated as a string concatination.
And
is treated as aditive operation.
The First Example
From the semantics, I'd say we're looking at
arithmetic promotion
at work. Note the first example:Due to arithmetic promotion, those two
char
values are promoted toString
values, so the types become:The
+
is overloaded, to perform concatenation because all operands are of typeString
.The Second Example
In the second example, as with all assignments, we evaluate the right hand side of the
=
operator first, and what do we have?The char is interpreted as its numerical value, because there is no
String
to cause promotion, and we have a numerical addition, which is then appended to theString
.Extra Reading
Some notes on arithmetic promotion can be found here.
Some notes on expression evaluation can be found here.
ret = ret + str.charAt(i) + str.charAt(i); // // it concatenates the letters correctly
This is because ret is string snd it concatenates with the other characters.
ret += str.charAt(i) + str.charAt(i); // it concatenates numbers
This is because the compiler first evaluates 'str.charAt(i) + str.charAt(i)' which probably results in a number and then concatenates it with ret. So essentially we evaluate the left side and then assign it.
Hope it clears your confusion.
The result of the following expression
is the result of String concatenation. The Java language specification states
The result of
is the result of the additive operator applied to two numeric types. The Java language specification states
In which case
becomes an
int
holding the sum of the twochar
values. That is then concatenated toret
.You might also want to know this about the compound assignment expression
+=
In other words
is equivalent to