[java] Creating a "logical exclusive or" operator in Java

Observations:

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

Problem:

Java has no logical XOR operator, according to sun. I would like to define one.

Method Definition:

As a method it is simply defined as follows:

public static boolean logicalXOR(boolean x, boolean y) {
    return ( ( x || y ) && ! ( x && y ) );
}


Method Call:

This method is called in the following way:

boolean myVal = logicalXOR(x, y);


Operator Usage:

I would much rather have an operator, used as follows:

boolean myVal = x ^^ y;


Question:

I can't find anything on how to go about defining a new operator in Java. Where should I start?

This question is related to java operators xor

The answer is


You can just write (a!=b)

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


you'll need to switch to Scala to implement your own operators

pipe example


A and B would have to be boolean values to make != the same as xor so that the truth table would look the same. You could also use !(A==B) lol.


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 ^.


This is an example of using XOR(^), from this answer

byte[] array_1 = new byte[] { 1, 0, 1, 0, 1, 1 };
byte[] array_2 = new byte[] { 1, 0, 0, 1, 0, 1 };

byte[] array_3 = new byte[6];

int i = 0;
for (byte b : array_1)
    array_3[i] = b ^ array_2[i++];

Output

0 0 1 1 1 0

Because boolean data type is stored like an integer, bit operator ^ functions like a XOR operation if used with boolean values.

//©Mfpl - XOR_Test.java

    public class XOR_Test {
        public static void main (String args[]) {
            boolean a,b;

            a=false; b=false;
            System.out.println("a=false; b=false;  ->  " + (a^b));

            a=false; b=true;
            System.out.println("a=false; b=true;  ->  " + (a^b));

            a=true;  b=false;
            System.out.println("a=true;  b=false;  ->  " + (a^b));

            a=true; b=true;
            System.out.println("a=true; b=true;  ->  " + (a^b));

            /*  output of this program:
                    a=false; b=false;  ->  false
                    a=false; b=true;  ->  true
                    a=true;  b=false;  ->  true
                    a=true; b=true;  ->  false
            */
        }
    }

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.


The only operator overloading in Java is + on Strings (JLS 15.18.1 String Concatenation Operator +).

The community has been divided in 3 for years, 1/3 doesn't want it, 1/3 want it, and 1/3 doesn't care.

You can use unicode to create method names that are symbols... so if you have a symbol you want to use you could do myVal = x.$(y); where $ is the symbol and x is not a primitive... but that is going to be dodgy in some editors and is limiting since you cannot do it on a primitive.


The following your code:

public static boolean logicalXOR(boolean x, boolean y) {
    return ( ( x || y ) && ! ( x && y ) );
}

is superfluous.

Why not to write:

public static boolean logicalXOR(boolean x, boolean y) {
    return x != y;
}

?

Also, as javashlook said, there already is ^ operator.

!= and ^ work identically* for boolean operands (your case), but differently for integer operands.

* Notes:
1. They work identically for boolean (primitive type), but not Boolean (object type) operands. As Boolean (object type) values can have value null. And != will return false or true when one or both of its operands are null, while ^ will throw NullPointerException in this case.
2. Although they work identically, they have different precedence, e.g. when used with &: a & b != c & d will be treated as a & (b != c) & d, while a & b ^ c & d will be treated as (a & b) ^ (c & d) (offtopic: ouch, C-style precedence table sucks).


That's because operator overloading is something they specifically left out of the language deliberately. They "cheated" a bit with string concatenation, but beyond that, such functionality doesn't exist.

(disclaimer: I haven't worked with the last 2 major releases of java, so if it's in now, I'll be very surprised)


Logical exclusive-or in Java is called !=. You can also use ^ if you want to confuse your friends.


Here is a var arg XOR method for java...

public static boolean XOR(boolean... args) {
  boolean r = false;
  for (boolean b : args) {
    r = r ^ b;
  }
  return r;
}

Enjoy


Here's an example:

Given 2 int values, return true if one is negative and one is positive. Except if the parameter "negative" is true, then return true only if both are negative.

    public boolean posNeg(int a, int b, boolean negative) {
      if(!negative){
        return (a>0 && b<0)^(b>0 && a<0);
      }
      else return (a<0 && b<0);
    }

I am using the very popular class "org.apache.commons.lang.BooleanUtils"

This method is tested by many users and safe. Have fun. Usage:

boolean result =BooleanUtils.xor(new boolean[]{true,false});

What you're asking for wouldn't make much sense. Unless I'm incorrect you're suggesting that you want to use XOR to perform Logical operations the same way AND and OR do. Your provided code actually shows what I'm reffering to:

public static boolean logicalXOR(boolean x, boolean y) {
    return ( ( x || y ) && ! ( x && y ) );
}

Your function has boolean inputs, and when bitwise XOR is used on booleans the result is the same as the code you've provided. In other words, bitwise XOR is already efficient when comparing individual bits(booleans) or comparing the individual bits in larger values. To put this into context, in terms of binary values any non-zero value is TRUE and only ZERO is false.

So for XOR to be applied the same way Logical AND is applied, you would either only use binary values with just one bit(giving the same result and efficiency) or the binary value would have to be evaluated as a whole instead of per bit. In other words the expression ( 010 ^^ 110 ) = FALSE instead of ( 010 ^^ 110 ) = 100. This would remove most of the semantic meaning from the operation, and represents a logical test you shouldn't be using anyway.


You can use Xtend (Infix Operators and Operator Overloading) to overload operators and 'stay' on Java


Isn't it x != y ?