Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 301
Chen Xie Avatar asked May 18 '18 00:05

Chen Xie


2 Answers

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
like image 108
shmosel Avatar answered Nov 13 '22 12:11

shmosel


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.

like image 5
Erwin Bolwidt Avatar answered Nov 13 '22 12:11

Erwin Bolwidt