• Post Reply Bookmark Topic Watch Topic
  • New Topic

can you bitwise and a boolean with an integer ?  RSS feed

 
Nikolas Nikolaou
Ranch Hand
Posts: 101
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi. I found a line of code In the Head First Java books that looks like a bitwise and between a Boolean and an Integer as a condition In a while loop.



Is this an error and the & Is supposed to be an && or Is It a legitimate expression ?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In line 3, you are not performing a bitwise AND between a boolean and an integer; you are performing a bitwise AND between two booleans. Adding braces to make the order of operations more clear:

So the left side is: !success
And the right side is: attempts++ < 200

which are both boolean expressions.

This is tricky code. There is a reason why & was used here instead of &&, and you have to understand the difference between the two:

  • The && operation short circuits. Since the result of A && B is true when A is true, no matter what B is, the && operator doesn't evaluate B if A is true, and immediately returns true.
  • The & operation does not short circuit. That means that both A and B will be evaluated, no matter whether A is true or false.


  • The difference is important here because the right hand side of the expression: attempts++ < 200 has a side effect: it increments attempts, using the ++ operator.

    If you would have used && instead of &, then attempts would not be incremented if !success is true (and the program would probably be stuck in an infinite loop).

    As you can see, this is quite tricky to understand. It's better to avoid such clever tricks when writing code, because it makes the program hard to understand for other people and even for yourself, when you look at your own code later. It would be better to write this code in a less tricky way, without relying on the non-short circuiting behaviour of & and not having a side effect in the boolean expression:

     
    Nikolas Nikolaou
    Ranch Hand
    Posts: 101
    1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks!
    I see the (attempts++ <200) as a whole now. I was seeing It as (Boolean & int) <200.This Is greatly due to my lack of knowledge and partly due to me drinking only one filter coffee.
     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!