The XOR Operator in Java

Mohammad Irfan Oct 12, 2023
  1. the XOR Operator ^ in Java
  2. XOR Using != Operator in Java
  3. Execute the XOR Using the &&, ||, and ! Operator in Java
The XOR Operator in Java

This tutorial introduces how to use the XOR operator in Java. We’ve also listed some example codes to guide you and help you understand the topic.

The XOR or exclusive OR is a logical operator used for bit manipulation and returns true only if both the boolean values are different; otherwise, it returns false.

For example, if two operands are true, the XOR will return false. If any of them is false, then the result will be true.

In this article, we will see how Java implements the XOR operator. Let’s see the examples.

the XOR Operator ^ in Java

In this example, we used the ^ operator to perform the XOR operations in two boolean operands or variables. It returns true if both the values are different; otherwise, it returns false. See the example below.

public class Main {
  public static void main(String[] args) {
    boolean a = true;
    boolean b = false;
    boolean c = true;

    System.out.println(a ^ b);
    System.out.println(b ^ c);
    System.out.println(c ^ a);
  }
}

Output:

true
true
false

XOR Using != Operator in Java

Apart from the ^ operator that we used in the previous example, we can also use the != (not equal to) operator to perform the XOR operation in Java.

This example program returns the same result as the one above.

public class Main {
  public static void main(String[] args) {
    boolean a = true;
    boolean b = false;
    boolean c = true;

    System.out.println(a != b);
    System.out.println(b != c);
    System.out.println(c != a);
  }
}

Output:

true
true
false

Execute the XOR Using the &&, ||, and ! Operator in Java

This method is another solution to get the XOR of two boolean values in Java; however, this solution is a little complex compared to the previous ones. Still, if it solves the problem, we can consider it.

See the example below.

public class Main {
  public static void main(String[] args) {
    boolean a = true;
    boolean b = false;
    boolean c = true;

    System.out.println((a || b) && !(a && b));
    System.out.println((b || c) && !(b && c));
    System.out.println((c || a) && !(c && a));
  }
}

Output:

true
true
false

Related Article - Java Operator