views:

430

answers:

3

The bitwise operators are supposed to travel the variables and operate on the bit by bit. In the case of integers, longs, chars this makes sense. These variables can contain the full range of values enforced by their size.

In the case of booleans, however, a boolean can contain only two values. 1 = true or 0 = false. But the size of the boolean isn't defined. It can be as big as a byte or as small a bit.

So what's the effect of using a bitwise operator on a boolean? Does the JVM essentially translate it to a normal logical operator and move on? Does it treat the boolean as a single bit entity for the purpose of the operation? Or is the result undefined along with the size of a boolean?

+2  A: 

Even if it will work you shouldn't do it. Language specs define bitwise operators only when both operands are of primitive integer types or both are of boolean type. I'd say for any other case the results are not defined:

http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#5228

see me no more
+8  A: 

The operators &, ^, and | are bitwise operators when the operands are primitive integral types. They are logical operators when the operands are boolean, and their behaviour in the latter case is specified. See the section 15.22.2 of the Java Language Specification for details.

Noel Ang
Ken
+3  A: 

Using the bitwise operator can circumvent short-circuiting behavior:

boolean b = booleanExpression1() && booleanExpression2();
boolean b = booleanExpression1() & booleanExpression2();

If booleanExpression1() evaluates to false, then
booleanExpression2() is not evaluated in the first case, and
booleanExpression2() (and whatever side-effects it may have) is evaluated in the second case,

mobrule
Good thing to keep in mind, thanks!
Daniel Bingham