Why does my String turn into Integers instead of letters after I add characters with +? [duplicate]

In Java the char primitive type is basically just a numeric value that maps to a character, so if you add two char values together they produce a number and not another char (and not a String) so you end up with an int as you’re seeing.

To fix this you can use the Character.toString(char) method like this:

s += Character.toString(str.charAt(i)) + Character.toString(str.charAt(i))

But this is all fairly inefficient because you’re doing this in a loop and so string concatenation is producing a lot of String objects needlessly. More efficient is to use a StringBuilder and its append(char) method like this:

StringBuilder sb = new StringBuilder(str.length() * 2);
for (int i = 0; i < str.length(); ++i) {
    char c = str.charAt(i);
    sb.append(c).append(c);
}
return sb.toString();

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)