0

Possible Duplicate:
What does the ^ operator do in Java?
The power ^ in Java?

I am sorry if this is a duplicate, but i didn´t found anything in SO.

So can someone explaint me why

     System.out.println((2^0));

this does return 2?

i was expecting a 1.

Community
  • 1
  • 1
SomeJavaGuy
  • 7,237
  • 2
  • 19
  • 33
  • 4
    ^ is xor, not the power operator – James Dec 27 '12 at 10:37
  • Suggested search in the future: `x operators`. Replace `x` with the language in question: it will cover most questions of "Why/What does a b ..?". –  Dec 27 '12 at 10:38

3 Answers3

8

Because the ^ operator does not mean "raise 2 to the 0th power". It's a bitwise exclusive OR operator.

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

In order to do that, your code should look like this:

double one = Math.pow(2.0, 0.0);  // Silly, but you can do it.

Don't be surprised if the answer comes out to something that's not exactly 1.0. You'll need to know about how floating point numbers work.

duffymo
  • 299,921
  • 44
  • 364
  • 552
6

The ^ sign means XOR and not pow. Try Math.Pow(2.0, 0.0) instead.

rekire
  • 46,262
  • 29
  • 163
  • 256
4

^ in Java is Bitwise exclusive-OR. so 2(1 0) ^(XOR) 0(0 0) =1 0 ie 2 !!! Got it?

Saty
  • 1,058
  • 11
  • 22