当添加 'a' + 'b'
时会产生 195。输出数据类型是 char
还是 int
?
最佳答案
添加 Java 字符、短裤或字节的结果是 int:
Java Language Specification on Binary Numeric Promotion :
- If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed. Then:
- If either operand is of type double, the other is converted to double.
- Otherwise, if either operand is of type float, the other is converted to float.
- Otherwise, if either operand is of type long, the other is converted to long.
- Otherwise, both operands are converted to type int.
But note what it says about compound assignment operators (like +=) :
The result of the binary operation is converted to the type of the left-hand variable ... and the result of the conversion is stored into the variable.
例如:
char x = 1, y = 2;
x = x + y; // compile error: "possible loss of precision (found int, required char)"
x = (char)(x + y); // explicit cast back to char; OK
x += y; // compound operation-assignment; also OK
找出结果类型的一种方法通常是将其转换为 Object 并询问它是什么类:
System.out.println(((Object)('a' + 'b')).getClass());
// outputs: class java.lang.Integer
如果您对性能感兴趣,请注意 Java bytecode甚至没有用于较小数据类型的算术专用指令。例如,对于加法,有指令iadd
(for ints), ladd
(for longs), fadd
(for floats), dadd
( double ),就是这样。为了用较小的类型模拟 x += y
,编译器将使用 iadd
然后使用 i2c
之类的指令将 int 的高字节归零>(“int 到 char”)。如果 native CPU 具有针对 1 字节或 2 字节数据的专用指令,则由 Java 虚拟机在运行时对其进行优化。
如果您想将字符连接为字符串而不是将它们解释为数字类型,有很多方法可以做到这一点。最简单的方法是在表达式中添加一个空字符串,因为添加一个字符和一个字符串会产生一个字符串。所有这些表达式都会产生字符串 "ab"
:
'a' + ""+ 'b'
""+ 'a' + 'b'
(这是因为""+ 'a'
首先被评估;如果""
code> 在最后而不是你会得到"195"
)new String(new char[] { 'a', 'b' })
new StringBuilder().append('a').append('b').toString()
String.format("%c%c", 'a', 'b')
关于java - 在Java中,两个字符相加的结果是int还是char?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8688668/