Disclosure: This article may contain affiliate links. When you purchase, we may earn a commission.

10 Examples of XOR Operator In Java

Hello guys, if you are wondering what does the XOR operator do in Java then you have come to the right place. XOR is a bitwise operator in Java, much like AND and OR and its very important because you can perform XOR operation using this operator. If you don't remember, XOR return true if the two values which you are comparing are different like one is true and other is false or vice-versa but it returns false or 0 if both operands are same like both are true or both are false. By using this technique you can solve many coding problems as you can check if the bits you are comparing is same or not. In this article, I will show you different example of XOR operator in Java after that you will understand this operator better. 

But, before we get to the 10 best examples of XOR Operator in Java that will teach you everything you need to know, let me tell you a little bit more about what it really is.

The XOR operator in Java is basically a bitwise operator that works by comparing the individual bits of many operands. XOR is actually the short form of exclusive OR and it will return a true value if and only if the two bits that you compare are not the same. 





10 Examples Of XOR Operator In Java

Since it is binary, you need to remember that 1 stand for true and 0 stands for false.

You can also make use of XOR in terms of other popular operators like OR, AND, and NOT. A simple rule of thumb is to remember that an XOR B value basically equates to (A AND (NOT B)) OR (B AND (NOT A)). 

1. How To Use The XOR Operator In Java

The XOR operator is represented by the '^' symbol in Java. What you need to understand is that it can be used on any primitive data type in Java. Loot at the following example: 

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

This code will give an output like this:

0 XOR 0: 0
0 XOR 1: 1
1 XOR 0: 1
1 XOR 1: 0

2. How To Use The XOR Operator With Boolean Values

XOR is a wonderful operator that can also work with boolean values. Using XOR, you can create a table using boolean true and false. Look at the following example:

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

If you run this program, you will get an output like this:

False XOR False: false
False XOR True: true
True XOR False: true
True XOR True: false


3. How To Use The XOR Operator With Integer Values In Java

The XOR operator can also be used with integers that are not 0 or 1. The operator will work with individual bits of the binary that is equivalent to the integer. You can see the following piece of code to get a better understanding:

public static void main(String[] args){
	System.out.println("9 XOR 15: " + (9 ^ 15));//1001 XOR 1111 = 0110
	System.out.println("1 XOR 20: " + (1 ^ 20));//00001 XOR 10100 = 10101
	System.out.println("7 XOR 7: " + (7 ^ 7));//0111 XOR 0111 = 0000
	System.out.print("32 XOR 0: " + (32 ^ 0));//100000 XOR 000000 = 100000
}

When you run this piece of code, you will get the following piece of code:

9 XOR 15: 6
1 XOR 20: 21
7 XOR 7: 0
32 XOR 0: 32

4. How To Use The XOR Operator With Binary Strings

As you know, the XOR Operator works only with primitive data types. But you can also write your own methods that make use of the XOR operator with the help of some additional logic. You can simply loop through each character of the two strings simultaneously. You then have to use the XOR operator on both strings. See the following program to gain a better understanding:

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

If you run this program, you will get the following output:

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



6. How To Find A Non Repeating Value Using XOR

Finding a non-repeating integer from an array can be a complex problem. But you can do it very efficiently by making use of the XOR operator. For example, look at the following code:

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

When you run this program, you will get the following output:

The non-repeating integer is:5



7. Simple Example Of The XOR Operator

Check out the following program for a simple example making use of the XOR operator:

public class XorDemo {
   public static void main(String[] args) {
      boolean a = true;
      boolean b = false;
      boolean result = a ^ b;
      System.out.println("a ^ b: "+ result); //prints the result true
 
      a = true;
      b = true;
      result = a ^ b;
      System.out.println("a ^ b: "+ result); //prints the result false
 
      a = false;
      b = true;
      result = a ^ b;
      System.out.println("a ^ b: "+ result); //prints the result true
 
      a = false;
      b = false;
      result = a ^ b;
      System.out.println("a ^ b: "+ result); //prints the result false
   }
}


8. Perform XOR On Two Integers

The following program will show you how to perform the XOR operator on two integer values:

public class XorDemo1 {
  public static void main(String[] args) {
    int x = 6;// Binary value of 6 is 0110
    int y = 10;// Binary value of 10 is 1010
    int result = x^y;// xor operation on 0110^1010 which gives 1100
        System.out.println("result: "+result);//integer value of 1100 is 12
   }
}

9. Calculating XOR

It is simple to learn how XOR compares two operands. If both the bits are the same, XOR will return 0. If both the bits are different, XOR will return 1. 

10. Difference Between & and && In Java

This is another common questions Java developer ask to me. Well, && is conditional, which means that it is performed on two boolean operands, on the other hand  & is bitwise, which means that it is performed on bit operands. It's also known as difference between bitwise and logical operator in Java


That's all about what is XOR operator in Java and how to use it. We have seen 10 example of using XOR operator in Java. We have seen how it works and you can use it solve bitwise problems. While in real life you may not be able to use XOR as often as + or % operator but is a definitely worth knowing and learning. If you are doing programming for embedded system or indulge in dealing with bytes, then XOR is a must know tool for you. 

Some Programming problems based on the bitwise operator :
  • How to swap two numbers without using a temp variable? (solution)
  • How to check if an integer is a power of two in Java? (solution)
  • How to find if the number is even or odd? (solution)
  • How to add two numbers without using the + operator in Java? (solution)
  • Write a method to remove duplicates from ArrayList in Java? (Solution)
  • How to find Greatest Common Divisor of two numbers in Java? (solution)
  • How to check if a number is Armstrong's number or not? (solution)
  • 10 Courses to Crack any Programming interview (courses)
  • How to check if LinkedList contains any cycle in Java? (solution)
  • How to find the Fibonacci sequence up to a given number? (solution)
  • How do find the largest and smallest number in an array? (solution)
  • How to solve the Producer-Consumer Problem in Java. (solution)
  • How to find prime factors of an integer in Java? (solution)
  • How to find the first non-repeated characters from String in Java? (program)


Thanks for reading this article so far. IF you like this Java tutorial on XOR operator then please share with your friends and colleagues. IF you have any questions or doubts feel free to ask. 


No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.