问题
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