java - 在java中,为什么前缀递增或递减运算符在字节情况下不需要强制转换

标签 java operators integer-promotion

在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/

相关文章:

c - 在存在 unsigned int 和 signed int 的 C 表达式中,哪种类型将提升为哪种类型?

c++ - 如何避免按位运算的积分提升

java - 更改ListView某一行的图标

java - 如果我们通过一个线程添加并通过另一个线程删除,我们是否需要同步?

c# - 或整数

c# - VB.net 中没有增量运算符

c - 整数如何提升为无符号整数

java - 上传带有附加信息的多个文件(Spring RestController)

java - 无法将 PDF 文件作为二进制数据获取

c# - 隐式 (bool) 和 == 运算符覆盖 - 正确处理 if 语句