+ 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

10th Sep 2020, 9:58 AM
Vinay_GB
Vinay_GB - avatar
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
10th Sep 2020, 11:49 AM
minirkk
minirkk - avatar
+ 15
Vinay_GB x = (y ^= (x ^= y))^x; weird but works fine. 😅
10th Sep 2020, 11:27 AM
minirkk
minirkk - avatar
+ 13
Vinay_GB 👍😇
10th Sep 2020, 11:59 AM
minirkk
minirkk - avatar
10th Sep 2020, 10:03 AM
The future is now thanks to science
The future is now thanks to science - avatar
+ 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. 😊
10th Sep 2020, 11:47 AM
Vinay_GB
Vinay_GB - avatar
+ 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
10th Sep 2020, 11:57 AM
Vinay_GB
Vinay_GB - avatar
+ 5
This works. x ^= y; y ^= x; x ^= y;
10th Sep 2020, 10:34 AM
Avinesh
Avinesh - avatar