A ^ = b ^ = a ^ = b in Java seems wrong

public class Main
{
    public static void main(String[] args)
    {
        int a,b,c,d;
        a=1;b=2;
        a^=b^=a^=b;
        System.out.println(a+" "+b);
        c=1;d=2;
        c^=d;
        d^=c;
        c^=d;
        System.out.println(c+" "+d);
    }
}

I use a ^ b ^ = a ^ = b to replace a and b. However, the output of this program

0 1
2 1

I am new in Java and I don’t know why a is 0. Is this a java runtime error? Or something special in Java I do not know? Here is the java version.

java version "1.7.0_65"
OpenJDK Runtime Environment (fedora-2.5.2.5.fc20-x86_64 u65-b17)
OpenJDK 64-Bit Server VM (build 24.65-b04, mixed mode)

Sorry, my first question is about stack overflow ... if I forgot some rules, please say thank you.

+4
source share
2 answers

Let's simplify it together

int a = 1;
int b = 2;
a ^= (b ^= (a ^= b));
System.out.println(a + " " + b);

is the same as saying

int a = 1;
int b = 2;
int a_tmp = a;
a = a_tmp ^ (b ^= (a ^= b));
System.out.println(a + " " + b);

, a ^ = (b ^ = (a ^ = b)) , a = (b ^ = (a ^ = b)), . , . , @duffymo, .

+4

, . , :

true ^ true = false  
true ^ false = true 
false ^ true = true 
false ^ false = false

a^=b^=a^=b;

: 0001 ^ 0010 ^ 0001 ^ 0010 0001 ^ 0010 = 0011. , 0010 ^ 0011 = 0001, . 0001 ^ 0001 = 0000, a = 0000 0.
  b: 0010 ^ 0001 ^ 0010 . 0001 ^ 0010 = 0011 0010 ^ 0011 = 0001, b = 0001 1. , a = 0000 0 b = 0001 1. , , .

0

All Articles