When you try to do something like this:
if (true ^ 1) { //do something }
the compiler reasonably says that operator ^
is not defined for argument types boolean and int. But if you use it like this:
if (true ^ 1 > 0) { //do something }
the code compiles (for Java 8 at least) and flawlessly works. Basically these operations:
false ^ -1 > 0 false ^ 1 > 0 true ^ -1 > 0 true ^ 1 > 0
Act like a valid logical XOR:
| ^ -----+-- F F | F F T | T T F | T T T | F
Could anybody please explain what happens under the hood?
Boolean values and operations C++ is different from Java in that type bool is actually equivalent to type int. Constant true is 1 and constant false is 0. It is considered good practice, though, to write true and false in your program for boolean values rather than 1 and 0.
A 0 (zero) is treated as false. Where as in JAVA there is a separate data type boolean for true and false.
Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true. To make life easier, C Programmers typically define the terms "true" and "false" to have values 1 and 0 respectively.
In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy. That is, all values are truthy except false , 0 , -0 , 0n , "" , null , undefined , and NaN . JavaScript uses type coercion in Boolean contexts.
It's simple: >
has higher precedence than ^
, so
if (true ^ 1 > 0) {
is equivalent to
if (true ^ (1 > 0)) {
which is equivalent to
if (true ^ true)
... which is just logical XOR.
I would never write code like this, mind you. I would be surprised to see an example which couldn't be written more clearly in a different way.
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