为什么一个 char + 另一个 char = 一个奇怪的数字

代码片段如下:

public static void main (String[]arg) 
{
    char ca = 'a' ; 
    char cb = 'b' ; 
    System.out.println (ca + cb) ; 
}

输出是:

195

为什么会这样?我认为 'a' + 'b' 将是 "ab""12"3.

Why is this the case? I would think that 'a' + 'b' would be either "ab" , "12" , or 3.

这是怎么回事?

推荐答案

+ 的两个 char 是算术加法,而不是字符串连接.你必须做类似 ""+ ca + cb,或者使用String.valueOfCharacter.toString方法保证+ 是一个String,用于操作符进行字符串连接.

+ of two char is arithmetic addition, not string concatenation. You have to do something like "" + ca + cb, or use String.valueOf and Character.toString methods to ensure that at least one of the operands of + is a String for the operator to be string concatenation.

如果 + 运算符的任一操作数的类型为 String,则该操作为字符串连接.

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 to a primitive numeric type, or a compile-time error occurs.

至于为什么你得到 195,那是因为在 ASCII 中,'a' = 97'b' = 98,以及 97 + 98= 195.

As to why you're getting 195, it's because in ASCII, 'a' = 97 and 'b' = 98, and 97 + 98 = 195.

这执行基本的 intchar 转换.

This performs basic int and char casting.

 char ch = 'a';
 int i = (int) ch;   
 System.out.println(i);   // prints "97"
 ch = (char) 99;
 System.out.println(ch);  // prints "c"

这忽略了字符编码方案的问题(初学者不应该担心......但是!).

This ignores the issue of character encoding schemes (which a beginner should not worry about... yet!).

作为注释,Josh Bloch 指出,很遗憾 + 对字符串连接和整数加法都进行了重载(对于字符串连接重载 + 运算符可能是一个错误." -- Java Puzzlers,谜题 11:最后的笑声).通过使用不同的字符串连接标记可以轻松避免很多此类混淆.

As a note, Josh Bloch noted that it is rather unfortunate that + is overloaded for both string concatenation and integer addition ("It may have been a mistake to overload the + operator for string concatenation." -- Java Puzzlers, Puzzle 11: The Last Laugh). A lot of this kinds of confusion could've been easily avoided by having a different token for string concatenation.

  • 是与空字符串连接进行字符串转换真的那么糟糕吗?

相关文章