I tried some code to swap two integers in Java without using a 3rd variable, using XOR.
Here are the two swap functions I tried:
package lang.numeric
I do not have enough reputation points to comment on Nathan's answer.
@Nathan Hughes response talking about the Java Puzzlers book is spot on, and his answer points to some insights that does allow you to do this in 1 line. Though not as elegantly as the OP's question.
As Nathan points out:
In the CleverSwap program, the variable x is sampled twice—once for each appearance in the expression—but both samplings occur before any assignments
As well as using https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html as a guide, you can do this in 1 line with:
a = ( b = (a = a ^ b) ^ b) ^ a;
The key being the assignment of the a variable value as part of the first XOR ensuring that you keep that on the left side of the second XOR (see the jls link above, for a good example of assignment in the left hand operand). Similarly, setting the b variable with the results of the second XOR, again keeping to the left of the final XOR.