Creating a "logical exclusive or" operator in Java

JavaOperatorsXor

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

Isn't it x != y ?

Solution 3 - Java

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

Solution 4 - Java

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

Solution 5 - Java

You can just write (a!=b)

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

Solution 6 - Java

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)

Solution 7 - Java

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

Solution 8 - Java

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

Solution 9 - Java

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.

Solution 10 - Java

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

Solution 11 - Java

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

Solution 12 - Java

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.

Solution 13 - Java

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});

Solution 14 - Java

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.

Solution 15 - Java

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

Solution 16 - Java

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
			*/
		}
	}

Solution 17 - Java

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);
    }

Solution 18 - Java

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

pipe example

Solution 19 - Java

Can be achieved using stream API in java 8 and above

public static boolean logicalXOR(boolean x, boolean y) {  // can modify to take [] or list of bools
    return Stream.of(x, y)  // modify as per method params
        .filter(bool -> bool)
        .count() == 1;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioneleven81View Question on Stackoverflow
Solution 1 - JavajavashlookView Answer on Stackoverflow
Solution 2 - JavaMaurice PerryView Answer on Stackoverflow
Solution 3 - JavastarblueView Answer on Stackoverflow
Solution 4 - JavaPeter LawreyView Answer on Stackoverflow
Solution 5 - JavaShuliyeyView Answer on Stackoverflow
Solution 6 - JavaKevin AndersonView Answer on Stackoverflow
Solution 7 - JavaDoradusView Answer on Stackoverflow
Solution 8 - JavaSashaView Answer on Stackoverflow
Solution 9 - JavaTofuBeerView Answer on Stackoverflow
Solution 10 - JavaTimothy JacobsenView Answer on Stackoverflow
Solution 11 - JavaigaView Answer on Stackoverflow
Solution 12 - Javauser2904660View Answer on Stackoverflow
Solution 13 - JavaAdam111pView Answer on Stackoverflow
Solution 14 - JavaJohn TheibertView Answer on Stackoverflow
Solution 15 - JavaAsyrafView Answer on Stackoverflow
Solution 16 - JavaLedónView Answer on Stackoverflow
Solution 17 - JavaSpicyCatGamesView Answer on Stackoverflow
Solution 18 - Javamut1naView Answer on Stackoverflow
Solution 19 - JavaHarsh GundechaView Answer on Stackoverflow