Java xor operator with example programs
Java Bitwise XOR operator:
In Java, you can use the ^ operator to perform a bitwise exclusive or (XOR) operation on two integers. The XOR operation compares each bit of the first number to the corresponding bit of the second number. If the bits are the same, the corresponding result bit is set to 0.
- Java bit wise Xor operator operates on bits of numbers.
- It will be represented as "^".
- XOR will return true if both bits are different.
- For example 1 XOR 0 gives 1. Ex: 1^0=1.
- 0^1=1.
Java Bitwise Xor:
Program#1:Java Example program on two integer numbers Xor operation.
- package com.Xorinjava;
- public class XOR {
- /**
- * Xor in java Xor example program
- * @author www.instanceofjava.com
- */
- public static void main(String[] args) {
- int a=1;
- int b=0;
- int c= a^b;
- System.out.println(c);
- }
- }
- 1
Program #2: java xor boolean expression : java example program
- package com.Xorinjava;
- public class XOR {
- /**
- * Xor in java boolean Xor example program
- * @author www.instanceofjava.com
- */
- public static void main(String[] args) {
- boolean a=true;
- boolean b=false;
- boolean c= a^b;
- System.out.println(c);
- System.out.println(false^false);
- System.out.println(true^true);
- }
- }
Output:
- true
- false
- false
Java Xor Strings:
- Gives compile time error.
- The operator ^ is undefined for the argument type(s) java.lang.String, java.lang.String
Program #4: Java Xor of two strings
- package com.Xorinjava;
- public class XOR {
- /**
- * Xor in java boolean Xor example program
- * @author www.instanceofjava.com
- */
- public static void main(String[] args) {
- String str="a";
- String str1="b";
- System.out.println(str^str1);// compile time error: The operator ^ is undefined for the
- argument type(s) java.lang.String, java.lang.String
- }
- }
Xor of Binary Strings:
Program #5: Java xor of two binary strings.
- package com.Xorinjava;
- public class XOR {
- /**
- * Xor in java String bits Xor example program
- * @author www.instanceofjava.com
- */
- 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);
- }
- }
- 0100100000