Conditional versus bitwise operators in conditional statements?

edited September 2014 in General Discussion

I noticed in one discussion the following conditional statement

if (key >= '0' & key <= '9') {
  // do something
}

where I would have used the conditional operator && the author has used the bitwise operator &

I understand there are circumstances where it is necessary to have both expressions evaluated (i.e. when an operand value in the second expression has to be changed irrespective of the first expression) but this is quite rare.

Personally I prefer to use conditional operators in preference to bitwise operators in conditional statements (except in the situation described in the previous paragraph). The main reason for this is shortcutting (i.e. the second expression does not always have to be evaluated).

AFAIK it is standard practice to use conditional operators rather than bitwise operators in a conditional statement WHEN they have the same overall effect, of course I could be wrong.

One final thought, in all the Java programming books (especially those for students) that I have read use the conditional operators, so perhaps we should promote their use in this forum?

I am interested to know what others think.

Answers

  • Answer ✓

    Well, indeed, 99.9 % of the time, we want the boolean operators, not the bitwise ones.

    I think the example you show had a typo or was made by somebody not knowing better.

    Boolean operators shortcut on the first expression making the conditional to fail or to success.

    You never want to write:

    if (someObject != null & someObject.isSomething())

    for example. It will throw an exception if someObject is null, unlike the version with &&

    Likewise, if you have

    if (call1() | call2() | call3())

    the three functions will be called, even if call1() is true. While with || the first true result will stop the evaluation.

    So, at least for performance reason, the boolean operators are preferred to the bitwise ones.

Sign In or Register to comment.