• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why bitwise operators can be used in boolean expressions?  RSS feed

 
Varun Chopra
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
true && true is equivalent to true & true.
If & is a bitwise operator and true/false are NOT bits, then why & can be used with true/false? Is it overloaded in Java?
 
Thomas Thevis
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it overloaded in Java?

Yes. '&' is also a boolean operator and works like '&&' except for the fact that it *always* evaluates both operands. Therfore, '&&' is called a short circuit operator and is in nearly all cases preferable.
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the bits of all "false"s are the same as all other "false"s, and the bits of all "true"s are the same as all other "true"s, then you can easily use the bitwise operators on them. You get which bits are the same with &, you get all the 1 bits with | and you get those which differ with ^. In fact you can use & | ^ on any primitives (I think) and compare their bits.

The one good use I can think of for & | rather than && || is to maintain precedence when used in conjunction with ^. Not that I use ^ on booleans very often.
 
Varun Chopra
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In fact you can use & | ^ on any primitives (I think) and compare their bits.


Yes, I tried this and it works:



But one thing to notice is applying bitwise operator on boolean gives a boolean as output, while doing the same on char and int gives an int back. I guess that proves | is overloaded in java.
[ October 10, 2008: Message edited by: Varun Chopra ]
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is, just like + is overloaded for Strings to concatenate instead of adding.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!