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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With