Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!

# XOR in java

kundana sharma
Greenhorn
Posts: 10
what does ^ do in java? I know that it is XOR which means it returns true only if both the arguments are true.
but I am not able to understand this.
public int xoring(int x,int y){
return (x^y);
what does this method do?please explain with an example.
The whole code snippet is this:

Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34837
369
An integer is really a list of binary digits. That code goes through the binary digits for 111 and 5 and xors each of them. So if you have two 1's or two 0's, that digit becomes a 0. And if you have one of each, it becomes a 1.

As a shorter example:
7 ^ 5

7: 0111
5: 0101
xor: 0010

Mike Simmons
Ranch Hand
Posts: 3090
14
kundana sharma wrote:what does ^ do in java? I know that it is XOR which means it returns true only if both the arguments are true.

Well, no. Before you read Jeanne's answer or try to understand how this works for integer arguments, you need to re-check this part. For boolean arguments, an XOR returns true of exactly one of the arguments is true - not if both are true:

false ^ false ==> false
false ^ true ==> true
true ^ false ==> true
true ^ true ==> false

Manu Barath
Greenhorn
Posts: 1
well kundana XOR means for unequal bit it gives true or 1 and for equal bits it gives false means 0
so according to your code snippit. it will gives 1101010 means 106

Campbell Ritchie
Sheriff
Posts: 49733
69
Welcome to the Ranch Manu Barath