In Java XOR with three true inputs returns true. Why?

Here's a Java 8 way of determining if exactly one boolean is true:

Stream.of(b1, b2, b3, ...)
        .filter(b -> b)
        .count() == 1;

Because true xor true = false, and false xor true is true. xor is associative, so group the values any way you please!

To decide that only one of them is true, you could add the values together as integers and see if the answer is 1.

I'm answering this as a general programming question, it really isn't particular to Java.


If you want a true result, if one and only one inputs is true you can use:

(a ^ b ^ c ) ^ ( a && b && c )

the test case result:

true true true = false
true true false = false
true false true = false
true false false = true
false true true = false
false true false = true
false false true = true
false false false = false

Tags:

Java

Logic

Xor