Java XOR (Exclusive or) operator on Booleans

In this tutorial, will show how to use a the Java XOR (exclusive or) operator on booleans, and we will discuss how the operator behaves with various combinations of boolean values.

In Java, booleans can hold only two values, true and false. The XOR operator in Java ‘ ^ ‘ can be used with booleans where it behaves in the same manner as it does within digital logic rules. The following table, called the truth table shows the output the operator provides for the different combinations of input for operation X Xor Y, where X and Y are boolean variables:

XYX ^ Y
falsefalsefalse
falsetruetrue
truefalsetrue
truetruefalse

The following code is an example of how to use the XOR operator:

public class test {
public static void main(String[] args) {

boolean x = false;
boolean y = false;
boolean xXorY = x ^ y;
System.out.println("false XOR false: " + xXorY); //false
x = false;
y = true;
xXorY = x ^ y;
System.out.println("false XOR true: " + xXorY); // true
x = true;
y = false;
xXorY = x ^ y;
System.out.println("true XOR false: " + xXorY); //true
x = true;
y = true;
xXorY = x ^ y;
System.out.println("true XOR true: " + xXorY); //false
}
}

The XOR operator examines the left hand side and the right hand side of the expression. The expression evaluates to true if and only if either the left
side or the right side evaluate to true, but not both. The following is the output of running the above program.

run:
false XOR false: false
false XOR true: true
true XOR false: true
true XOR true: false
BUILD SUCCESSFUL (total time: 0 seconds)

The operator is useful when you want to make sure that both X and Y are not the same.

Contents

Summary

The Xor operator is useful in cases where we want only one condition to be true. In this tutorial we discussed the possible combinations of input and output when we use the Xor operator.

Java XOR (Exclusive or) operator on Booleans
Scroll to top