在下面的三个按位左移代码片段中,Java 对示例 #2 和 #3 的处理方式不同,这很有趣。在最后一个示例(#3)中,为什么 Java 决定不将复合赋值语句升级为 int?
答案是否与 Java“内联”做事有关。非常感谢任何评论。
byte b = -128;
// Eg #1. Expression is promoted to an int, and its expected value for an int is -256.
System.out.println(b << 1);
b = -128;
// Eg #2. Must use a cast, otherwise a compilation error will occur.
// Value is 0, as to be expected for a byte.
System.out.println(b = (byte)(b << 1));
b = -128;
// Eg #3. Not only is no cast required, but the statement isn't "upgraded" to an int.
// Its value is 0, as to be expected for a byte.
System.out.println(b <<= 1);
最佳答案
复合赋值运算符,例如 +=
和 -=
和 <<=
等在它们的操作中有一个隐式类型转换。
换句话说。
byte x = 1;
x <<= 4;
等于:
byte x = 1;
x = (byte)(x << 4);
编译时。
左移操作仍然适本地提升变量(在 byte
的情况下为 int
)但复合赋值运算符为您转换它。
关于Java:复合赋值和基于表达式的类型提升,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19859237/