Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does (boolean ^ int > 0) work?

Tags:

java

syntax

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?

like image 479
Pavel Avatar asked Jan 25 '17 14:01

Pavel


People also ask

Is bool always 0 or 1?

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.

Is 0 false or true in Java?

A 0 (zero) is treated as false. Where as in JAVA there is a separate data type boolean for true and false.

Is it true 1 or 0?

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.

Does Java have truthy values?

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.


1 Answers

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.

like image 50
Jon Skeet Avatar answered Oct 20 '22 00:10

Jon Skeet