Is it bad to explicitly compare against boolean constants e.g. if (b == false) in Java?

It's not necessarily bad, it's just superfluous. Also, the actual variable name weights a lot. I would prefer for example if (userIsAllowedToLogin) above if (b) or even worse if (flag).

As to the performance concern, the compiler optimizes it away at any way.

Update: as to the authoritative sources, I can't find something explicitly in the Sun Coding Conventions, but at least Checkstyle has a SimplifyBooleanExpression module which would warn about that.


You should not use the first style. I have seen people use:

  • if ( b == true )
  • if ( b == false )

I personally find it hard to read but it is passable. However, a big problem I have with that style is that it leads to the incredibly counter-intuitive examples you showed:

  • if ( b != true )
  • if ( b != false )

That takes more effort on the part of the reader to determine the authors intent. Personally, I find including an explicit comparison to true or false to be redundant and thus harder to read, but that's me.


This is strongly a matter of taste.

Personally I've found that if (!a) { is a lot less readable (EDIT: to me) than if (a == false) { and hence more error prone when maintaining the code later, and I've converted to use the latter form.

Basically I dislike the choice of symbols for logic operations instead of words (C versus Pascal), because to me a = 10 and not b = 20 reads easier than a == 10 && !(b==20), but that is the way it is in Java.

Anybody who puts the "== false" approach down in favour of "!" clearly never had stared at code for too long and missed that exclamation mark. Yes you can get code-blind.