I don’t understand the output from the following code:
public static void main(String[] args) { int i1, i2, i3, i4; byte b; i1 = 128; b = (byte) i1; i2 = (int) b; i3 = 0 | b; i4 = 1 << 7; System.out.format('i1: %d b: %d i2: %d i3: %d i4: %d\n', i1, b, i2, i3, i4); }
Output:
i1: 128 b: -128 i2: -128 i3: -128 i4: 128
Because byte is an 8-bit two’s-complement signed integer, the binary representations with a 1 in the most significant bit are interpreted as negative values, which is why b becomes -128, which I’m totally fine with. I also understand that it’s probably a good idea to keep the interpretation consistent when casting, as with i2. But shouldn’t i3 and i4 have identical bit patterns and therefore map to identical int values?
Sign extension is what is making
i2andi3negative.In the expression
(0 | b),bis promoted to an int, and sign extension occurs as part of this promotion.That’s not happening in the expression assigned to
i4. The constants1and7are already ints so there’s no sign extension involved.