Importance of XOR operator in Java?


Bitwise XOR (exclusive or) "^" is an operator in Java that provides the answer '1' if both of the bits in its operands are different, if both of the bits are same then the XOR operator gives the result '0'. XOR is a binary operator that is evaluated from left to right. The operator "^" is undefined for the argument of type String.

Example1

public class XORTest1 {
   public static void main(String[] args) {
      boolean x = false;
      boolean y = false;
      boolean xXorY = x ^ y;
      System.out.println("false XOR false: "+xXorY);

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

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

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

Output

false XOR false: false
false XOR true: true
true XOR false: true
true XOR true: false


Example2

public class XORTest2 {
   public static void main(String[] args) {
      String str1 = "1010100101";
      String str2 = "1110000101";
      StringBuffer sb = new StringBuffer();

      for (int i = 0; i < str1.length(); i++) {
         sb.append(str1.charAt(i)^str2.charAt(i));
      }
      System.out.println(sb);
   }
}

Output

0100100000
raja
Published on 09-Aug-2019 10:15:08
Advertisements