File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes the Exclusive OR operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "the Exclusive OR operator" Watch "the Exclusive OR operator" New topic

the Exclusive OR operator

Celinio Fernandes
Ranch Hand

Joined: Jun 28, 2003
Posts: 549

I have a very basic question:
Exclusive or means that if the two operand bits are different the result is 1; otherwise the result is 0

I read in a book that 2^5 evaluates to 7. How is that possible ?

SCJP 1.4, SCWCD 1.4, SCBCD 1.3, SCBCD 5
Visit my blog
Rick Beaver
Ranch Hand

Joined: Dec 14, 2004
Posts: 464

So, the result of an XOR would be

ph34r my 133t j4v4 h4><0r1ng sk177z
Celinio Fernandes
Ranch Hand

Joined: Jun 28, 2003
Posts: 549

I still dont get it: shouldn't the result be 1 or 0 ?
Why are we adding the 2 operands here ?
[ September 22, 2005: Message edited by: Max longbeach ]
Edwin Keeton
Ranch Hand

Joined: Jul 10, 2002
Posts: 214

The operands 2 and 5 are not being added, although addition in this case produces the same result, which may be confusing you. The operands are the individual bits that represent each number in binary notation, not decimal notation.

Here's another example 2^3=1.

The ^ XOR operator works at the bit level, so convert the decimal numbers to binary:
2 = 0010
3 = 0011
^ = 0001

Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
You are thinking of a single-bit, exclusive-or operation:

0 EXOR 0 is 0
0 EXOR 1 is 1
1 EXOR 0 is 1
1 EXOR 1 is 0

But the Java ^ operation on integral types is a bitwise operation.
The operation defined above is applied to all the bits of the ^ operands,
in parallel, as the previous poster demonstrated.

Also note than ^ is defined for booleans, and does want you wish: the
result is true iff the operand have different boolean values:

false ^ false is false
false ^ true is true
true ^ false is true
true ^ true is false

But then again, you get the same result with boolean's == operation.

There is no emoticon for what I am feeling!
I agree. Here's the link:
subject: the Exclusive OR operator
It's not a secret anymore!