davidcesarino
davidcesarino

Reputation: 16228

What's the difference between XOR and NOT-EQUAL-TO?

My question uses Java as an example, but I guess it applies to probably all.

Is there any practical difference between the XOR operator (^ in Java) and the not-equal-to operator (!= in Java), when comparing booleans?

I evaluated things here, but I just kept wondering (seems weird, two things equal)... and didn't find anything on the net. Just one discussion in some forum that ended quickly without any result.

Upvotes: 44

Views: 21473

Answers (6)

Jack
Jack

Reputation: 133609

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)

Upvotes: 30

Jon Skeet
Jon Skeet

Reputation: 1502656

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.

Upvotes: 46

Vlad
Vlad

Reputation: 35594

With boolean values, there should be no difference. You should choose whichever is more appropriate for your sense of operation.

Example:

bool oldChoice = ...;
bool newChoice = ...;
if (oldChoice != newChoice)
    ...

Here XOR would give the same result, but will not reflect the real code intention.

Upvotes: 3

LukeH
LukeH

Reputation: 269558

Yes, you can use XOR to test booleans for (in)equality, although the code is less intuitive: if (x ^ y) versus if (x != y).

Upvotes: 5

Teson
Teson

Reputation: 6736

There's a big difference, XOR works at bit-level, keeping differences as ones, so 0b0011 xor 0b1101 => 0b1110

regards, //t

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490418

They should be essentially the same in this case.

Upvotes: 0

Related Questions