Why can I add characters to strings but not characters to characters?

前端 未结 7 829
陌清茗
陌清茗 2020-12-21 09:18

So I wanted to add a character to a string, and in some cases wanted to double that characters then add it to a string (i.e. add to it itself first). I tried this as shown b

7条回答
  •  半阙折子戏
    2020-12-21 09:52

    char + char returns an int so the compiler complains that String string = (int), which is indeed wrong.

    To concatenate the chars, you can use the empty String ("") at the beginning so the + operator will be for String concatenation or use a StringBuilder that can append chars as well.

    char s = 'X';
    String string = new StringBuilder().append(s).append(s).toString();
    

    Note: the char variable is s, not X.

提交回复
热议问题