wood burning stoves 2.0
The moose likes Beginning Java and the fly likes XOR in java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "XOR in java" Watch "XOR in java" New topic
Forums: Java in General Beginning Java

XOR in java

kundana sharma

Joined: Sep 09, 2012
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

Joined: May 26, 2003
Posts: 33132

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

answer is 2

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3028
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

Joined: Dec 26, 2012
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

Joined: Oct 13, 2005
Posts: 46435
Welcome to the Ranch Manu Barath
I agree. Here's the link: http://aspose.com/file-tools
subject: XOR in java
It's not a secret anymore!