Java: compound assignment and expression based type promotion

孤人 提交于 2019-12-11 04:51:48

问题


In the three bitwise left shift code fragments below, it's interesting that examples #2 and #3 are treated differently by Java. In the last example (#3), why does Java decide not to upgrade the compound assignment statement to an int?

Does the answer have something to do with Java doing things "inline". Thanks a lot for any comments.

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);

回答1:


Compound assignment operators e.g += and -= and <<=, etc have a implicit type cast in their operation.

In other words.

byte x = 1;
x <<= 4;

is equal to:

byte x = 1;
x = (byte)(x << 4);

when compiled.

The left-shift operation still promotes the variables appropriately (in the case of byte to an int) but the compound assignment operator casts it for you.




回答2:


println b <<= 1

is the same as

b = (byte) (b << 1)
println b

So this implies the cast to byte as well as your second example.



来源:https://stackoverflow.com/questions/19859237/java-compound-assignment-and-expression-based-type-promotion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!