Exclusive “or” (xor
) Logical Operator
In some scripting languages like PHP, there exists a logical operator (e.g. &&
, ||
, and
, or
, etc.) called the “Exclusive Or”. The exclusive or evaluates two booleans. It then returns true if exactly one of the two expressions are true, false otherwise. For example:
// since both are false false xor false == false // exactly one of the two expressions are true true xor false == true // exactly one of the two expressions are true false xor true == true // Both are true. "xor" only returns true if EXACTLY one of the two expressions evaluate to true. true xor true == false
How to create a Logical Operator in Java
As Java does not ship out the box with this functionality, we can easily create it ourselves.
To create an xor
logical operator
, or exclusive or
as it is sometimes referred to, we can look to implement the following:
The solution in Java
In Java we can use the caret
character to perform an XOR operation.
public class XOR { public static boolean xor(boolean a, boolean b) { // using the caret character return a ^ b; } }
Some test cases to validate our method
import static org.junit.Assert.*; import org.junit.Test; public class XORTest { private static void testing(boolean actual, boolean expected) { assertEquals(expected, actual); } @Test public void testBasic() { System.out.println("Testing basics."); testing(XOR.xor(false, false), false); testing(XOR.xor(true, false), true); testing(XOR.xor(false, true), true); testing(XOR.xor(true, true), false); } @Test public void testNested() { System.out.println("Testing nested calls."); testing(XOR.xor(false, XOR.xor(false, false)), false); testing(XOR.xor(XOR.xor(true, false), false), true); testing(XOR.xor(XOR.xor(true, true), false), false); testing(XOR.xor(true, XOR.xor(true, true)), true); testing(XOR.xor(XOR.xor(false, false), XOR.xor(false, false)), false); testing(XOR.xor(XOR.xor(false, false), XOR.xor(false, true)), true); testing(XOR.xor(XOR.xor(true, false), XOR.xor(false, false)), true); testing(XOR.xor(XOR.xor(true, false), XOR.xor(true, false)), false); testing(XOR.xor(XOR.xor(true, true), XOR.xor(true, false)), true); testing(XOR.xor(XOR.xor(true, XOR.xor(true, true)), XOR.xor(XOR.xor(true, true), false)), true); } }