Bitwise XOR Operator in Java

JavaJavaBeginner
Practice Now

Introduction

The XOR operator is a bitwise operator used in Java to compare individual bits of the operands. In Java, the XOR operator is represented by the caret symbol (^). It is used to compare two bits and returns true if and only if the two bits being compared are not the same.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/booleans("`Booleans`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/for_loop("`For Loop`") java/BasicSyntaxGroup -.-> java/if_else("`If...Else`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/SystemandDataProcessingGroup -.-> java/string_methods("`String Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117997{{"`Bitwise XOR Operator in Java`"}} java/classes_objects -.-> lab-117997{{"`Bitwise XOR Operator in Java`"}} java/class_methods -.-> lab-117997{{"`Bitwise XOR Operator in Java`"}} java/modifiers -.-> lab-117997{{"`Bitwise XOR Operator in Java`"}} java/oop -.-> lab-117997{{"`Bitwise XOR Operator in Java`"}} java/identifier -.-> lab-117997{{"`Bitwise XOR Operator in Java`"}} java/arrays -.-> lab-117997{{"`Bitwise XOR Operator in Java`"}} java/booleans -.-> lab-117997{{"`Bitwise XOR Operator in Java`"}} java/comments -.-> lab-117997{{"`Bitwise XOR Operator in Java`"}} java/data_types -.-> lab-117997{{"`Bitwise XOR Operator in Java`"}} java/for_loop -.-> lab-117997{{"`Bitwise XOR Operator in Java`"}} java/if_else -.-> lab-117997{{"`Bitwise XOR Operator in Java`"}} java/operators -.-> lab-117997{{"`Bitwise XOR Operator in Java`"}} java/output -.-> lab-117997{{"`Bitwise XOR Operator in Java`"}} java/strings -.-> lab-117997{{"`Bitwise XOR Operator in Java`"}} java/variables -.-> lab-117997{{"`Bitwise XOR Operator in Java`"}} java/string_methods -.-> lab-117997{{"`Bitwise XOR Operator in Java`"}} java/system_methods -.-> lab-117997{{"`Bitwise XOR Operator in Java`"}} end

Using XOR with Primitive Data Types

In Java, the XOR operator can be used with any primitive data type. Let's verify the truth table of XOR using primitive data types.

public class XOR {
    public static void main(String[] args) {
        System.out.println("0 XOR 0: " + (0 ^ 0)); // Output: 0
        System.out.println("0 XOR 1: " + (0 ^ 1)); // Output: 1
        System.out.println("1 XOR 0: " + (1 ^ 0)); // Output: 1
        System.out.print("1 XOR 1: " + (1 ^ 1)); // Output: 0
    }
}

To run the code, save it to the file ~/project/XOR.java, and execute the following commands in the terminal:

cd ~/project/
javac XOR.java
java XOR

Using XOR with Boolean Values

XOR can also work with boolean values. Let's recreate the table using boolean true and false.

public class XOR {
    public static void main(String[] args) {
        System.out.println("False XOR False: " + (false ^ false)); // Output: false
        System.out.println("False XOR True: " + (false ^ true)); // Output: true
        System.out.println("True XOR False: " + (true ^ false)); // Output: true
        System.out.print("True XOR True: " + (true ^ true)); // Output: false
    }
}

To run the code, save it to the file ~/project/XOR.java, and execute the following commands in the terminal:

cd ~/project/
javac XOR.java
java XOR

Using XOR with Integer Values

XOR operator can be used on integers that are not 0 or 1. The XOR operator will work on the individual bits of the binary equivalent of the integer.

public class XOR {
    public static void main(String[] args) {
        System.out.println("9 XOR 15: " + (9 ^ 15)); // Output: 6
        System.out.println("1 XOR 20: " + (1 ^ 20)); // Output: 21
        System.out.println("7 XOR 7: " + (7 ^ 7)); // Output: 0
        System.out.print("32 XOR 0: " + (32 ^ 0)); // Output: 32
    }
}

To run the code, save it to the file ~/project/XOR.java, and execute the following commands in the terminal:

cd ~/project/
javac XOR.java
java XOR

Finding the Non-repeating Integer using XOR

The XOR operator can also be used to find the non-repeating integer in an array of integers.

public class XOR {
    public static int nonRepeatingInteger(int[] numArray) {
        int xor = numArray[0];
        for (int i = 1; i < numArray.length; i++)
            xor = xor ^ numArray[i];
        return xor;
    }

    public static void main(String[] args) {
        int[] arr = {10, 12, 5, 6, 10, 6, 12};
        int nonRepeatingNum = nonRepeatingInteger(arr);
        System.out.print("The non-repeating integer is: " + nonRepeatingNum);
    }
}

To run the code, save it to the file ~/project/XOR.java, and execute the following commands in the terminal:

cd ~/project/
javac XOR.java
java XOR

The output will be:

The non-repeating integer is: 5

Finding XOR of Binary Strings

XOR only works for primitive data types. However, we can write our own method that uses the XOR operator and some additional logic to find the XOR of two binary strings.

public class XOR {
    public static String binaryStringXOR(String binStr1, String binStr2) {
        String xor = "";
        // adding zeroes to make the two strings equal in length
        if (binStr1.length() > binStr2.length()) {
            String temp = "";
            for (int i = 0; i < binStr1.length() - binStr2.length(); i++)
                temp += "0";
            binStr2 = temp + binStr2;
        } else if (binStr2.length() > binStr1.length()) {
            String temp = "";
            for (int i = 0; i < binStr2.length() - binStr1.length(); i++)
                temp += "0";
            binStr1 = temp + binStr1;
        }
        for (int i = 0; i < binStr1.length(); i++) {
            xor += binStr1.charAt(i) ^ binStr2.charAt(i);
        }
        return xor;
    }

    public static void main(String[] args) {
        System.out.println("1001 XOR 1111: " + binaryStringXOR("1001", "1111"));
        System.out.println("1 XOR 10100: " + binaryStringXOR("1", "10100"));
        System.out.println("0111 XOR 1: " + binaryStringXOR("0111", "1"));
        System.out.print("100000 XOR 0: " + binaryStringXOR("100000", "0"));
    }
}

To run the code, save it to the file ~/project/XOR.java, and execute the following commands in the terminal:

cd ~/project/
javac XOR.java
java XOR

The output will be:

1001 XOR 1111: 0110
1 XOR 10100: 10101
0111 XOR 1: 0110
100000 XOR 0: 100000

Summary

In this lab, we learned about the basic concepts of the XOR operation in Java. We have demonstrated how the XOR operators can be used on boolean and integer data types. We have also implemented a method to find the XOR of two binary strings and a method to find the non-repeating integer in an array of integers.

Other Java Tutorials you may like