Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this statement not working in java x ^= y ^= x ^= y;

int x=1;
int y=2;
x ^= y ^= x ^= y;

I am expecting the values to be swapped.But it gives x=0 and y=1. when i tried in C language it gives the correct result.

like image 442
sadananda salam Avatar asked Oct 02 '10 08:10

sadananda salam


People also ask

What does Y x mean in Java?

It's the Addition assignment operator. Let's understand the += operator in Java and learn to use it for our day to day programming. x += y in Java is the same as x = x + y. It is a compound assignment operator. Most commonly used for incrementing the value of a variable since x++ only increments the value by one.

What does X * mean in Java?

In Java, the *= is called a multiplication compound assignment operator. It's a shortcut for density = density * invertedRatio; Same abbreviations are possible e.g. for: String x = "hello "; x += "world" // results in "hello world" int y = 100; y -= 42; // results in y == 58.

What does this X do in Java?

this is a reference to the current object, and is implicitly passed into non static methods. this. x dereferences the reference to get to the "x" attribute. Use it if you want to disambiguate between a function argument and a class member.

What is the meaning of '?' In Java?

it means: if(min >= 2) someval =2; else someval =1. Its called a ternary operator See this java example too.


1 Answers

Your statement is roughly equivalent to this expanded form:

x = x ^ (y = y ^ (x = x ^ y));

Unlike in C, in Java the left operand of a binary operator is guaranteed to be evaluated before the right operand. Evaluation occurs as follows:

x = x ^ (y = y ^ (x = x ^ y))
x = 1 ^ (y = 2 ^ (x = 1 ^ 2))
x = 1 ^ (y = 2 ^ (x = 3))
x = 1 ^ (y = 2 ^ 3)             // x is set to 3 
x = 1 ^ (y = 1)
x = 1 ^ 1                       // y is set to 1
x = 0                           // x is set to 0

You could reverse the order of the arguments to each xor expression so that the assignment is done before the variable is evaluated again:

x = (y = (x = x ^ y) ^ y) ^ x
x = (y = (x = 1 ^ 2) ^ y) ^ x
x = (y = (x = 3) ^ y) ^ x 
x = (y = 3 ^ y) ^ x             // x is set to 3
x = (y = 3 ^ 2) ^ x
x = (y = 1) ^ x
x = 1 ^ x                       // y is set to 1
x = 1 ^ 3
x = 2                           // x is set to 2

This is a more compact version that also works:

x = (y ^= x ^= y) ^ x;

But this is a truly horrible way to swap two variables. It's a much better idea to use a temporary variable.

like image 137
Mark Byers Avatar answered Oct 08 '22 01:10

Mark Byers