Search code examples
javaif-statementoperatorsbitwise-operators

Difference between Bitwise and boolean operator 'AND'


Possible Duplicates:
logical operators in java
What's the difference between | and || in Java?

As the title says, I need to know the difference between & operator and && operator. Can anyone help me in simple words.

  1. How do they differ from each other?
  2. And which one to be used in a IF statement?

Solution

  • There are in fact three "and" operators:

    • a && b, with a and b being boolean: evaluate a. If true, evaluate b. If true, result is true. Otherwise, result is false. (I.e. b is not evaluated if a is not true.)
    • a & b, with a and b being boolean: evaluate both, do logical and (i.e. true only if both are true).
    • a & b, where a and b are both integral types (int, long, short, char, byte): evaluate a and b, and do a bitwise AND.

    The second one can be viewed as a special type of the third one, if one sees boolean as a one-bit integral type ;-)

    As the top-level condition of an if-statement you can use the first two, but the first one is most likely useful. (I.e. there are not many cases where you really need the second and the first would do something wrong, but the other way around is more common. In most cases the first is simply a little bit faster.)