Java Reference
In-Depth Information
The Bitwise and Logical Operators
The following operators are referred to as the bitwise and logical operators :
& : the AND operator
^ : the exclusive OR operator
| : the inclusive OR operator
&& : the conditional AND operator
|| : the conditional OR operator
The & , ^ , and | operate on expressions where both operands are either primitive numeric
types or both are boolean expressions. When operating on numeric types, they are bitwise
operators. When operating on boolean types, they are logical operators. The && and || operators
require both operands to be boolean expressions, so they are strictly logical operators.
The term bitwise refers to the & , ^ , and | operators performing a bitwise AND or OR
of the two operands. Table 1.3 shows the result of the possible outcomes for each of these
three operators.
TABLE 1.3
The Bitwise Operators
& (AND)
^ (exclusive OR)
| (inclusive OR)
0 & 0 is 0
0 ^ 0 is 0
0 | 0 is 0
0 & 1 is 0
0 ^ 1 is 1
0 | 1 is 1
1 & 0 is 0
1 ^ 0 is 1
1 | 0 is 1
1 & 1 is 1
1 ^ 1 is 0
1 | 1 is 1
Notice the & operator results in 1 only when both operands are 1, while the | operator
results in 0 only when both operators are 0. The exclusive OR ^ is 1 when the two operands
are different; otherwise it is 0.
The bitwise operators are evaluated on integer types. To compute the result, you need
to know the binary representation of the values. For example, what is the result of the
following expression?
int result = 12 ^ 45;
Begin by converting the 12 and 45 to binary numbers and align them vertically. Then
perform the exclusive OR on each column, as Figure 1.15 shows.
 
Search WWH ::




Custom Search