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

前端 未结 7 811
陌清茗
陌清茗 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:51

    It's because String + Char = String, similar to how an int + double = double.

    Char + Char is int despite what the other answers tell you.

    String s = 1; // compilation error due to mismatched types.

    Your working code is (String+Char)+Char. If you had done this: String+(Char+Char) you would get a number in your string. Example:

    System.out.println("" + ('x' + 'x')); // prints 240
    System.out.println(("" + 'x') + 'x'); // prints xx - this is the same as leaving out the ( ).
    

提交回复
热议问题