Why can I add characters to strings but not charac

2019-08-05 14:26发布

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 below.

char s = 'X'; 
String string = s + s;

This threw up an error, but I'd already added a single character to a string so I tried:

String string = "" + s + s;

Which worked. Why does the inclusion of a string in the summation cause it to work? Is adding a string property which can only be used by characters when they're converted to strings due to the presence of a string?

7条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-05 15:24

String string = "" + X + X;

is an example of concatenation. By pre-pending the empty string you specify that the result should be a string. The first line of code tells the compiler that you are adding 2 chars (or ints) which should result in an int, and not a string.

查看更多
登录 后发表回答