FAQ

Java

JSP

Servlet


Advertisement



How do compound assignment operator work for byte primitives?

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.


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |