4

I have expected both expression's will give same answer:

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

Output:

2
4

Is there a specific reason why 2^0*2 = 2 and (2^0)*2 = 4?

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
Prakash VL
  • 77
  • 7

3 Answers3

10

You have wrongly assumed that ^ operator behaves the same like the exponentiation in math.

At the first sight you can see that ^ is understood as + operator. Actually it means bitwise XOR operator.

System.out.println(2^0*2);   //  2 XOR 0  * 2 = 2
System.out.println((2^0)*2); // (2 XOR 0) * 2 = 4
System.out.println(2^4);     //  2 XOR 4      = 6

The XOR is exclusive disjunction that outputs true only when inputs differ. Here is the whole trick:

2^0 = 2 XOR 0 = (0010) XOR (0000) = (0010) = 2 
2^4 = 2 XOR 4 = (0010) XOR (0100) = (0110) = 6
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
2

check this link

http://bmanolov.free.fr/javaoperators.php

2^0*2=2

  • has higher priority thatn ^ so first you will evaluate 0*2 which is 0 and then xor it with 2 which will resutl 2

(2^0)*2

() has higher priority so you will first evaluate 2^0 then which is 2 then multiply it with 2

Amer Qarabsa
  • 6,412
  • 3
  • 20
  • 43
-3

Operator Precedence

In your first example you calculate: 0*2 = 2 ^ 0 = 2

In your second example you calculate: 2 ^ 0 = 2 * 2 = 4

Tim L
  • 165
  • 1
  • 6