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
?
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
?
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
check this link
http://bmanolov.free.fr/javaoperators.php
2^0*2=2
(2^0)*2
() has higher priority so you will first evaluate 2^0 then which is 2 then multiply it with 2
In your first example you calculate: 0*2 = 2 ^ 0 = 2
In your second example you calculate: 2 ^ 0 = 2 * 2 = 4