Java Reference
In-Depth Information
true
. In other words, it evaluates to
false
if both operands are
false
or if both
operands are
true
. Unlike the
&&
and
||
operators, this one must always evalu‐
ate both operands. The
^
operator is much more commonly used as a bitwise
operator on integer operands. With
boolean
operands, this operator is equiva‐
lent to the
!=
operator.
a
x
Bitwise and Shift Operators
The bitwise and shift operators are low-level operators that manipulate the individ‐
ual bits that make up an integer value. The bitwise operators are not commonly
used in modern Java except for low-level work (e.g., network programming). They
are used for testing and setting individual flag bits in a value. In order to understand
their behavior, you must understand binary (base-2) numbers and the two's comple‐
ment format used to represent negative integers.
You cannot use these operators with floating-point,
boolean
, array, or object
operands. When used with
boolean
operands, the
&
,
|
, and
\^
operators perform a
different operation, as described in the previous section.
If either of the arguments to a bitwise operator is a
long
, the result is a
long
. Other‐
wise, the result is an
int
. If the left operand of a shift operator is a
long
, the result is
a
long
; otherwise, the result is an
int
. The operators are:
Bitwise complement (
~
)
The unary
~
operator is known as the bitwise complement, or bitwise NOT,
operator. It inverts each bit of its single operand, converting 1s to 0s and 0s to
1s. For example:
byte
b
=
~
12
;
// ~00001100 = => 11110011 or -13 decimal
flags
=
flags
&
~
f
;
// Clear flag f in a set of flags
Bitwise AND (
&
)
This operator combines its two integer operands by performing a Boolean
AND operation on their individual bits. The result has a bit set only if the cor‐
responding bit is set in both operands. For example:
10
&
7
// 00001010 & 00000111 = => 00000010 or 2
if
((
flags
&
f
)
!=
0
)
// Test whether flag f is set
When used with
boolean
operands,
&
is the infrequently used Boolean AND
operator described earlier.
Bitwise OR (
|
)
This operator combines its two integer operands by performing a Boolean OR
operation on their individual bits. The result has a bit set if the corresponding
bit is set in either or both of the operands. It has a zero bit only where both
corresponding operand bits are zero. For example:
10
|
7
// 00001010 | 00000111 = => 00001111 or 15
flags
=
flags
|
f
;
// Set flag f