Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a "logical exclusive or" operator in Java

People also ask

What is && and || in Java?

The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.

Is exclusive or a logical operator?

Exclusive or (XOR, EOR or EXOR) is a logical operator which results true when either of the operands are true (one is true and the other one is false) but both are not true and both are not false.


Java does have a logical XOR operator, it is ^ (as in a ^ b).

Apart from that, you can't define new operators in Java.

Edit: Here's an example:

public static void main(String[] args) {
    boolean[] all = { false, true };
    for (boolean a : all) {
        for (boolean b: all) {
            boolean c = a ^ b;
            System.out.println(a + " ^ " + b + " = " + c);
        }
    }
}

Output:

false ^ false = false
false ^ true = true
true ^ false = true
true ^ true = false

Isn't it x != y ?


Java has a logical AND operator.
Java has a logical OR operator.

Wrong.

Java has

  • two logical AND operators: normal AND is & and short-circuit AND is &&, and
  • two logical OR operators: normal OR is | and short-circuit OR is ||.

XOR exists only as ^, because short-circuit evaluation is not possible.


Perhaps you misunderstood the difference between & and &&, | and || The purpose of the shortcut operators && and || is that the value of the first operand can determine the result and so the second operand doesn't need to be evaluated.

This is especially useful if the second operand would results in an error. e.g.

if (set == null || set.isEmpty())
// or
if (list != null && list.size() > 0)

However with XOR, you always have to evaluate the second operand to get the result so the only meaningful operation is ^.


You can just write (a!=b)

This would work the same as way as a ^ b.