What's the difference between XOR and NOT-EQUAL-TO?
For Boolean values, they mean the same thing - although there's a compound assignment operator for XOR:
x ^= y;
There's no equivalent compound assignment operator for inequality.
As for why they're both available - it would be odd for XOR not to be available just because it works the same way as inequality. It should logically be there, so it is. For non-Boolean types the result is different because it's a different result type, but that doesn't mean it would make sense to remove XOR for boolean
.
As stated in the Java Language Specification:
The result of != is false if the operands are both true or both false; otherwise, the result is true. Thus != behaves the same as ^ (§15.22.2) when applied to boolean operands.
In addition if you try looking at bytecode of a simple snippet:
void test(boolean b1, boolean b2) {
boolean res1 = b1^b2;
boolean res2 = b1!=b2;
}
you obtain:
test(ZZ)V
L0
LINENUMBER 45 L0
ILOAD 1
ILOAD 2
IXOR
ISTORE 3
L1
LINENUMBER 46 L1
ILOAD 1
ILOAD 2
IXOR
ISTORE 4
L2
LINENUMBER 47 L2
RETURN
L3
This assures that, in addition to the same semantics, there's no any actual practical difference in implementation. (you can also see that internally ints are used to store boolean values)
Yes, you can use XOR to test booleans for (in)equality, although the code is less intuitive: if (x ^ y)
versus if (x != y)
.