301

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?

6
  • 1
    what? the link you gave has the content 'bitwise exclusive OR' Commented Mar 10, 2015 at 13:37
  • were you wondering then if you could define operators in Java like you can in C++? Commented May 27, 2015 at 23:59
  • 1
    It seems you misunderstood the difference between & and &&. Both are logical operators (on a boolean). Starblue's answer covers it more widely. Commented Aug 4, 2016 at 10:45
  • just because it is not in the tutorial, does not mean that Java does not have it - tutorials are not (always) complete. See Java Language Specification 15.22.2 Commented Aug 19, 2016 at 9:24
  • 8
    It's called !=, there is also a logical XNOR called == Commented Mar 12, 2018 at 20:42

18 Answers 18

762

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 
Sign up to request clarification or add additional context in comments.

9 Comments

This escaped my memory too when I wrote my post, but I think you CAN use ^ as a logical operator (as well as bitwise).
^ is not only a bitwise operator. It is also a logical operator. The ^ operator is overloaded. It operates on integral types or boolean types. +1 for a great answer javashlook. Eddie, it doesn't get more explicit than JLS Section 15.22.2, "Boolean Logical Operators &, ^, and |".
And of course, the answer is that && and || will skip evaluating the 2nd part of the expression and & and | will always evaluate both parts of the expression (from my read of JLS). A ^^ would always have to evaluate both parts, by definition, so behaves identically to ^. Probably why there's no ^^
@Eddie: That and ^^ just looks too much like an emoticon.
Maybe it's a matter of semantics, but when it comes to XOR, bitwise and logical yield the same result. Therefore, no need for distinct operators. The simplified truth table for a XOR operator is X ^ !X = 1. You cannot short circuit an input in XOR because you have to determine whether the inputs are different. It is a lot easier to understand if you know the fabrication of the actual XOR gate.
|
337

Isn't it x != y ?

13 Comments

If x and y are booleans, then the logic table for xor and != are identical: t,t => f ; t,f => t; f,t => t; f,f => f
Maurice: Arrgh you just blew my mind! How did I never notice this?
@Milhous Are you saying a != b != c won't work, but a ^ b ^ c will? In that case, you are wrong.
Maurice, just brilliant! It happens to me to lose simple things from sight when there is a lot to do:)
This approch implodes when both sides are wrapper classes, new Boolean(true) != new Boolean(true) gives true.
|
78

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.

8 Comments

Interesting comment. Is that documented?
@Krzysztof Jabłoński They are bitwise operators on numbers, but here we are talking about boolean expressions.
@user666412 Yes, in the Java Language Specification (where else?).
If it has 2 AND operators and 2 OR operators then the statements 'Java has a logical AND operator' and 'Java has a logical OR operator' are not wrong. By definition if you have 2 of something then you also have 1 of it.
Can't help but take it seriously when someone returns a one word sentence reply!
|
35

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

Comments

26

You can just write (a!=b)

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

2 Comments

The expression (a != b) and (a ^ b) are not equivalent. The != (not equal) operator checks if the values of two variables are different, while the ^ (bitwise XOR) operator performs a bitwise XOR operation on the binary representations of two values. Assume a = 25 (binary: 11001) and b = 30 (binary: 11110). 1. (a != b) would be true because 25 is not equal to 30. 2. (a ^ b) would be 7 because the bitwise XOR of 25 and 30 is 7 (binary: 00111).
They are the same if a and b are booleans, as specified in the question.
15

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

2 Comments

The expression (a != b) and (a ^ b) are not equivalent. The != (not equal) operator checks if the values of two variables are different, while the ^ (bitwise XOR) operator performs a bitwise XOR operation on the binary representations of two values. Assume a = 25 (binary: 11001) and b = 30 (binary: 11110). 1. (a != b) would be true because 25 is not equal to 30. 2. (a ^ b) would be 7 because the bitwise XOR of 25 and 30 is 7 (binary: 00111).
I was referring to logical exclusive-or, not bitwise. By "logical" I meant that it operates on boolean, for which != and ^ do the same thing. For other data types besides boolean, yes, they are different.
10

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

4 Comments

For Boolean values I like !=
@GKalnytskyi for Boolean values != works incorrectly. For boolean values it's ok.
!= and ^ do not work identically for boolean operands. You'll get different results for "false & false != true" versus "false & false ^ true" because of precedence.
@AlbertHendriks, I'd better say that they work identically, but have different precedence (though it's just a matter of terminology).
9

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)

1 Comment

Bear in mind that you can't define new operators in C++ either. All you can do is give new meanings to the old ones.
7

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.

Comments

6

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

1 Comment

This feels like its going to have some very strange behaviour. E.g. XOR(true,true,true) returns true, which seems not like what you'd expect from a method called XOR. My expected behaviour would be that it always returns false (which is of course not helpful)
2

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

1 Comment

Note that Xtend doesn't allow you to override the caret ^; you must use bool_1.xor(bool_2). Oddly, the parser doesn't even allow you to use the caret; you must use xor for booleans and bitwiseXor for integers. You could, of course, overload another operator, but that would get very confusing.
2

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.

Comments

2

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

Comments

1

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.

Comments

1

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 

Comments

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

Comments

0

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

pipe example

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.