Pavel
Pavel

Reputation: 323

Why does (boolean ^ int > 0) work?

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?

Upvotes: 29

Views: 2717

Answers (4)

MatWdo
MatWdo

Reputation: 1740

Because order (priority) of operations is important, > has higher priority than ^

Here, first we check 1 > 0 and then first operation is XORed (^) with first result

Is equivalent to if(true ^ (1 > 0 ))

But, of course You can't XORed boolean with int

Upvotes: 3

Andremoniy
Andremoniy

Reputation: 34900

Because operation > has higher priority than ^, so it is equivalent to true ^ (1>0) which is operating with same types (boolean ^ boolean).

Upvotes: 11

Jon Skeet
Jon Skeet

Reputation: 1500165

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.

Upvotes: 78

GhostCat
GhostCat

Reputation: 140427

1 is of type int.

1 > 0 is of type boolean.

^ means XOR; and you can't XOR boolean and int.

In other words: the first expression "1" evaluates to a number; the second expression "1> 0" evaluates to boolean logic. The reason behind that is the operator predecence.

Upvotes: 10

Related Questions