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);
Compound assignment operators eg +=
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.