This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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 Android Security Essentials Live Lessons this week in the Android 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
internet detective

Joined: May 26, 2003
Posts: 30138

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

[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3003
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: 38087
Welcome to the Ranch Manu Barath
Don't get me started about those stupid light bulbs.
subject: XOR in java
Similar Threads
.txt file to char array
Why is applet on some browsers...
GRRRR! compile error!!!
Graphics2D compiler error
Stopping Animation