在java中假设我有以下代码片段
byte b = 127;
b=-b ;//(which require a cast due to numeric promotion)
b=++b; //does not require cast
最佳答案
++
的 JLS 规范说:
The type of the prefix increment expression is the type of the variable.
.... Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the prefix decrement expression is the value of the variable after the new value is stored.
(术语“缩小原始转换”指的是类型转换...)
引用:JLS 15.15.1 .
因此 ++b
是一个 byte
,不需要显式转换。
关于java - 在java中,为什么前缀递增或递减运算符在字节情况下不需要强制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28378928/