jlelse's Blog

Thoughts, stories and ideas

XOR Operator in Java

Published on in 👨‍💻 Dev
Short link: https://b.jlel.se/s/466
Share online  Translate 

At work today I came across an Eclipse feature for cleaning up Java code. It helps you to improve the code, for example to add final to attributes or parameters, or to improve boolean expressions.

By chance I stumbled upon the operator for XOR (exclusive OR - only exactly one of the options is true). For XOR, you can just use a simple ^. This was new to me, even though I’ve been using Java since school days (more than 5 years).

jshell> boolean one = true;
one ==> true

jshell> boolean two = false;
two ==> false

jshell> (one && !two) || (!one && two);
$3 ==> true

jshell> one ^ two;
$4 ==> true

jshell> one ^ one;
$5 ==> false

jshell> two ^ two;
$6 ==> false

Because it is a bitwise operator, it can also compare any primitive type:

jshell> 1 ^ 2; // 00000001 and 00000010
$7 ==> 3

jshell> 1 ^ 3; // 00000001 and 00000011
$8 ==> 2

Tags:

Jan-Lukas Else
Interactions & Comments