• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

XOR in java

 
kundana sharma
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 34218
341
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
Mike Simmons
Ranch Hand
Posts: 3041
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch Manu Barath
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic