How to handle Boolean values in Java through bitwise operators
Consider this example
int i=11,j=5; boolean b=true,c=false; System.out.println(b&c); // --> output=false System.out.println(i&j); // --> output=1
How do bit positions and operators handle Boolean variables?
Solution
Boolean values in java have no bitwise operation
&Ampere; And | do not perform bitwise operations in Java, but logical operations (as specified in § 15.22.2 of the JLS)
>&Is a logical and (calculated as true if and only if both parameters are true) > | is a logical or (calculated as true if and only if at least one parameter is true)
Note that the same operators are used for bitwise operations, but they only apply to types where both operands are convertible to integer types (that is, byte, char, short, int, long and their respective wrappers)
Since this article has triggered some heated discussions, I think I will clarify my insistence on the difference between "bitwise" and "logical" operations
First: Yes, to some extent, the two operations will be exactly the same, except for their input size (they may even be the same due to optimization)
However, there are at least three levels:
>Java language
The Java language specification defines Boolean as a primitive type with the two values true and false It does not define numerical values for these values, nor does it have a direct method to convert them to numeric types, and vice versa (see the last sentence of § 4.2.2) > java virtual machine
The Java virtual machine specification defines the boolean type, but it provides little support
It also talks about transformation
The easiest way to meet this requirement in the JVM is obviously to make 1 true, 0 false, and convert the operation to no operation This is also the most likely implementation, but it is not necessarily the only correct implementation. > Hardware
This has changed a lot, but most CPUs do not support Boolean types (why do you do this?) Therefore, the Boolean operation will use the conventional bitwise operation