这个问题在这里已经有了答案:
Java - char, int conversions
(4 个回答)
3年前关闭。
引用自 Think Java 书:
"Normally in Java, the statement x++ is exactly equivalent to x = x+1. But if x is a char, it's not exactly the same! In that case, x++ is legal, but x = x+1 causes an error."
谁能解释一下并举个例子?提前致谢!
最佳答案
Binary Numeric Promotion将在 binary + operator 的操作数上执行:
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.
所以,
x + 1
的结果是 int
它占用 32 位,而 char
占用16位。来自 int
的类型转换到 char
可能会损失准确性,你必须明确地这样做:char x = 1;
x = (char)(x+1);
关于Java char 类型增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49450640/