Why does it output integers?
The + operator is overloaded in Java to perform String concatenation only for String
s, not char
s.
From the Java Spec:
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 your case, char is converted to its primitive value (int), then added.
Instead, use StringBuilder.append(char)
to concatenate them into a String
.
If performance is not a concern, you could even do:
char c = 'A';
String s = "" + c + c;
and s += "" + c + c;
That will force the + String
concatenation operator because it starts with a String
(""). The Java Spec above explains with examples:
The + operator is syntactically left-associative, no matter whether it
is determined by type analysis to represent string concatenation or
numeric addition. In some cases care is required to get the desired
result. For example [...]
1 + 2 + " fiddlers"
is "3 fiddlers"
but the result of:
"fiddlers " + 1 + 2
is "fiddlers 12"