+ 12
What's the use of XOR(^) operator in Java?
I have been trying to swap values of two variables using XOR operator in C++ as well as in Java. In C++, using XOR operator I can swap two values easily, but in Java, it doesn't swapping two values. Instead, assigning value of one variable(and setting its value 0) to another one. I would be glad if anyone could help me understand the use of XOR operator in Java and how does this operator working in my code below. https://code.sololearn.com/cG4eFg5ZPLod/?ref=app
7 odpowiedzi
+ 16
in c++ this
x ^= y ^= x ^= y;
is working fine.
c++ don't follow priority.
Vinay_GB
edit: (sorry for tagging you again and again)
https://stackoverflow.com/questions/22003084/order-of-evaluation-for-c-vs-java
+ 15
Vinay_GB
x = (y ^= (x ^= y))^x;
weird but works fine. 😅
+ 13
Vinay_GB 👍😇
+ 8
Thanks for sharing those helpful links, Samsil Arefeen[Less Active] bro. 🙂🙏
Thanks for fixing the bug, Avinesh bro. 😊🙏
Thanks for the one-liner solution, RKK bro. 😄🤗
It took me some time to understand the logic behind it.
So, according to operator priorities your statement would work like:
1. (x ^= y)
2. (y ^= (x..))
3. x = (y..) ^ x;
Same as @Avinesh bro's solution. However, thanks for the efficient solution, bro. 😊
+ 7
"...edit: (sorry for tagging you again and again)"
- RKK
No problem, bro. It's my pleasure to learn something I don't know. :D
+ 5
This works.
x ^= y;
y ^= x;
x ^= y;