Home Java Master-java Java XOR Operator
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Java XOR Operator

Advertisement
Bitwise XOR (exclusive or) "^" is a Java operator that provides the answer 1 if both of the bits in its operands are different. But if both of the bits are same then the XOR operator gives the result 0.

Bitwise XOR (exclusive or) "^" is a Java operator that provides the answer 1 if both of the bits in its operands are different. But  if both of the bits are same then the XOR operator gives the result 0. Following example will show how to use "^" operator in Java.

XOR is a binary operator that is evaluated from left to right.

Example of Java XOR operator:

In the example below, the corresponding bits of both operands are 1 and 0, hence we get 1 as output because the bits are different.

a = 0000 0101

b = 0000 0110

a ^ b = 0000 0111

"^" operator work on bit , so it will produces 1 if any the operands will be different i.e. 1 and 0. But if both bit are 0 (0^0) and 1 (1^1) it will produces 0. In more simple word , if both bit are same then it will produce 0 but if both bit are different it will produce 1.

public class XorOperators{

public static void main(String args[])
{
int a=5,b=6,c=0;
c=a^b; // use of "^" operator
System.out.println("Result of a ^ b = "+c);
}
}
Output:

a=0000 0101 (5)
b=0000 0110 (6)

Result of a^b:
c=0000 0011 (3)

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 10, 2013

Ask Questions?    Discuss: Java XOR Operator  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com