The method public char charAt(int index)
returns a char
, so the line
str1 += str.charAt(i) + str.charAt(i);
performs the +
operator on two char
s.
According to the Java Specs:
15.18. Additive Operators
The operators + and - are called the additive operators.
AdditiveExpression:
MultiplicativeExpression
AdditiveExpression + MultiplicativeExpression
AdditiveExpression - MultiplicativeExpression
The additive operators have the same precedence and are syntactically left-associative (they group left-to-right).
If the type of either operand of a + operator is String
, then the operation is string concatenation.
Otherwise, the type of each of the operands of the + operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.
In every case, the type of each of the operands of the binary - operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.
so a char +
a char is addition, not concatenation.
Every char
is actually an integer value that is interpreted as an character.
Section 15.15.3 of the Java Specs says:
15.15.3. Unary Plus Operator +
The type of the operand expression of the unary + operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.
Unary numeric promotion (§5.6.1) is performed on the operand. The type of the unary plus expression is the promoted type of the operand. The result of the unary plus expression is not a variable, but a value, even if the result of the operand expression is a variable.
At run time, the value of the unary plus expression is the promoted value of the operand.
Therefore, adding two char
s produces an int
. When you +=
that int
, it is converted to a String
concatenated to said string.
To fix this problem, you can use any of the answers to this question: How to convert a char to a String?, e.g.
str1 += String.valueOf(str.charAt(i)) + str.charAt(i);
or
str1 += "" + str.charAt(i) + str.charAt(i);