& operator is applicable to booleans


While I thought binary operator & in Java was designed to work with integer types, it appeared to be perfectly applicable to boolean operands and worked exactly the same way as &&:

//always true:
assertTrue(boolean1 & boolean2 == boolean1 && boolean2); 

See more things that I still discover about Java.

  1. #1 by Sergey on Февраль 10, 2006 - 07:45

    suspicious! maybe it’s just a warper for integer data type then? just like in C++ ;)

  2. #3 by Chris Burnley on Март 17, 2006 - 08:28

    Yes the difference between & and && (for booleans) is that the second operand is always evaulated regardless of whether the statement is known to be true or false.

    I.e. the common idiom
    if(obj != null && obj.equals(someOtherObject))
    …;

    does not thrown a null pointer because if th statement is found to be false the second operand isn’t evaluated ( this is called a «short circuit» sometimes )

    if you were to do the same thing with «&», a null pointer would result.

    Oh and btw in response to Sergey, if you look at the bytecode you’ll see that there are no boolean specific bytecode (except perhaps getfield); they are treated as ints

  3. #4 by Alexey on Март 17, 2006 - 20:24

    Yeah Chris this is what Stas said in Russian (see link above). But don’t worry I’ve already started punishing people for commenting in a language other than the one of a posting.

Обязательно надо войти в систему для комментирования.