为什么 char +另一个字符 = 一个奇怪的数字
这是代码片段:
public static void main (String[]arg)
{
char ca = 'a' ;
char cb = 'b' ;
System.out.println (ca + cb) ;
}
输出是:
195
为什么会这样?我认为 'a' + 'b'
可能是 "ab"
、 "12"
或 3.
这是怎么回事?
Here's the code snippet:
public static void main (String[]arg)
{
char ca = 'a' ;
char cb = 'b' ;
System.out.println (ca + cb) ;
}
The output is:
195
Why is this the case? I would think that 'a' + 'b'
would be either "ab"
, "12"
, or 3
.
Whats going on here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
两个
char
的+
是算术加法,而不是字符串连接。您必须执行类似"" + ca + cb
的操作,或者使用String.valueOf
和Character.toString
方法来确保至少有一个+
的操作数是一个String
,用于运算符进行字符串连接。JLS 15.18 加法运算符
至于为什么你得到 195,这是因为在 ASCII 中,
'a' = 97
和'b' = 98
,以及97 + 98 = 195< /代码>。
这将执行基本的
int
和char
转换。这忽略了字符编码方案的问题(初学者不应该担心......但是!)。
作为注释,Josh Bloch 指出,非常不幸的是,
+
对于字符串连接和整数加法都被重载(“为字符串连接重载 + 运算符可能是一个错误。”—— Java Puzzlers,谜题 11:笑到最后)。通过使用不同的字符串连接标记可以轻松避免很多此类混乱。另请参阅
+
of twochar
is arithmetic addition, not string concatenation. You have to do something like"" + ca + cb
, or useString.valueOf
andCharacter.toString
methods to ensure that at least one of the operands of+
is aString
for the operator to be string concatenation.JLS 15.18 Additive Operators
As to why you're getting 195, it's because in ASCII,
'a' = 97
and'b' = 98
, and97 + 98 = 195
.This performs basic
int
andchar
casting.This ignores the issue of character encoding schemes (which a beginner should not worry about... yet!).
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.See also
我不会说 Java,但 195 是 97 + 98 =
a
和b
的 ASCII 代码。显然,ca
和cb
被解释为它们的整数值,可能是因为+
加法似乎不会导致字符串连接自动地。I don't speak Java, but 195 is 97 + 98 = the ASCII codes for
a
andb
. So obviously,ca
andcb
are interpreted as their integer values, probably because of the+
addition which does not seem to lead to a string concatenation automatically.如果您希望 + 运算符的结果为 String,则必须使用 String 类型作为操作数。
您应该这样写:
应用于 char 操作数的 + 运算符的行为就像算术和。
If you want to have a String as result of the + operator you have to use type String as operands.
You should write:
The + operator applied on char operands behaves as the arithmetic sum.
+
运算符不像对字符串那样对字符进行操作。这里发生的情况是,a
和b
被转换为它们的整数 ASCII 代码点 - 97 和 98 - 然后相加。The
+
operator doesn't operate over characters like it does over strings. What's happening here is thata
andb
are being cast to their integer ASCII codepoints - 97 and 98 - and then added together.