Java char 类型增量

标签 java char increment

这个问题在这里已经有了答案:





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/

相关文章:

java - JNDI 连接适用于 Tomcat,但不适用于 Websphere

java - JUnit RunListener 在失败()时被删除

C++如何将大字符串放入固定字符数组中

java - 将java方法转换为cpp

java - 我如何使用 launch4j 包装一个也提供命令行界面的 GUI 应用程序?

c - 如何在函数之间更改指针值

c - 为什么在第一个代码中它不起作用但在第二个代码中起作用? - 逆波兰表示法

java - 在数据库中插入新行时增加 ID

java - 如何在循环内增加数组的大小

c++ 取消引用迭代器时 x++ 和 x = x + 1 之间的区别