在下面的三个按位左移代码片段中,有趣的是示例 #2 和 #3 在 Java 中的处理方式不同。在最后一个示例(#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);