简单的Java代码会返回一些意外的结果

Lio*_*ion 1 java bit-manipulation

以下最简单的Java代码返回一些意外的输出.我们来看看吧.

package interchange;

final public class Main
{
    public static void main(String[] args)
    {
        int x = 15;
        int y = 20;

        x^=y^=x^=y;
        System.out.println("x = " + x + "; y = " + y);
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码在控制台上显示以下输出.

x = 0; y = 15
Run Code Online (Sandbox Code Playgroud)

怎么样?

szh*_*hem 6

根据运算符优先级,它可以像这样重写

x^=y; // 15 ^ 20 = 27, x = 27
y^=27; // 20 ^ 27 = 15, y = 15
x^=15; // 15 ^ 15 = 0, x = 0
Run Code Online (Sandbox Code Playgroud)