Java "x += y" and "x = x+y" yields different result

Chen Xie :

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.

shmosel :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=471978&siteId=1