I came up with two expressions to assign value from a bit operation to a variable, and noticed "x+=y" and "x=x+y" yielded different results in this case:
public void random ()
{
int n = 43261596;
System.out.println(Integer.toBinaryString(n));
n = n + 0&1; //binary representation of n is 0
//n += 0&1; //result is the same as n
System.out.println(Integer.toBinaryString(n));
}
I did some research, and found the only case "x+=y" and "x=x+y" is not equivalent is when operant types are not the same, however in this case, "n" is type of int
, and "0&1" shoud be a type of int
(according to this question Why does bitwise AND of two short values result in an int value in Java?:
Because the Java Language Specification says that the result of non-long integer arithmetic is always an int.)
So I'm wondering why it yields different results.
The difference is operator precedence. +
has precedence to &
, but &
has precedence to +=
. So your operations translate to this:
n = (n + 0) & 1; // = n & 1 = 0 (when n is even)
n += (0 & 1); // = n + 0 = n
The operator & has a lower precedence than +.
What you have actually written is:
n = ( n + 0 ) &1;
I added parentheses to clarify.
Since n is an even number, the outcome of that expression is zero.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With