| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
XyzWs Java FAQ:
How do compound assignment operator work for byte primitives?
Printer-friendly version |
Mail this to a friend
|
Advertisement
|
What is the result of 'byte x = 100; x += 100;'?The following example is from the Is 'x+=a' always equivalent to 'x=x+a'?
public class Program {
public static void main(String [] args){
byte x = 100;
System.out.println(x += 100);
}
}
output -56 The result seems not quite expected at first. Let's see what happens step by step: Firstly we expand the compound operator += to: byte x = 100; x = (byte)(x + 100); Secondly, the addition gets evaluated: x + 100 = 200. Then, the implicit conversion occurs: 200 int type is converted to the type of byte: 00000000 00000000 00000000 11001000 -> 11001000. Java simply truncate the higher bits that won't fit the size of the destination type. For a byte value, the first bit is the sign. Since the first bit is 1, 110001000 is a negative number. To figure out the value of the number, just flip all the bits and then add 1 to it: 11001000 -> 00110111 00110111 + 1 ------------- 00111000 00111000 is 56. That's why the final result is -56. |