consider this example please
int i=11, j=5;
boolean b=true, c=false;
System.out.println(b&c); // --> output=false
System.out.println(i&j); // --&g
There are no bitwise operations on boolean
in Java.
&
and |
don't do bitwise operations in Java, but logical operations (as specified in §15.22.2 of the JLS).
&
is the logical AND (it will evaluate to true
if and only if both arguments are true
)|
is the logical OR (it will evaluate to true
if and only if at least one of the arguments is true
).Note that the same operators are used for bitwise operations, but those only apply when both operands are of a type that is convertible to an integral type (i.e. byte
, char
, short
, int
, long
and their respective wrappers).
Since this post led to some ... spirited discussion, I think I'll clarify my insistence on the difference between "bitwise" and "logical" operations.
First of: Yes, at some level, the two operations will work exactly the same, except for the size of their input (which might even be identical, due to optimizations).
But, there are at lest 3 levels here:
The Java language
The Java language specification defines boolean
as a primitive type with the two values true and false. It does not define numeric values for those values and there is no direct way to convert it to a numeric type or vice versa (see last sentence of §4.2.2)
The Java Virtual Machine
The Java Virtual Machine Specification defines the boolean type but provides very little support for it.
It also says this about conversions
The Java virtual machine encodes
boolean
array components using 1 to represent true and 0 to represent false. Where Java programming languageboolean
values are mapped by compilers to values of Java virtual machine typeint
, the compilers must use the same encoding.
The easiest way to fullfil this requirement in a JVM is obviously to let 1
be true
and 0
be false and let the conversion operation be a no-op. That's also the most likely implementation, but it's not necessarily the only correct implementation.
The Hardware
This varies a lot, but most CPUs don't have support for a boolean
type (why should they?) so operations on boolean
will use normal bitwise operations here.