Java Reference
In-Depth Information
Table 4-4.
List of Boolean Logical Operators
Operators
Meaning
Type
Usage
Result
!
!true
false
Logical NOT
Unary
&&
true && true
true
Short-circuit AND
Binary
&
true & true
true
Logical AND
Binary
||
true || false
true
Short-circuit OR
Binary
|
true | false
true
Logical OR
Binary
^
true ^ true
false
Logical XOR(Exclusive OR )
Binary
&=
test &= true
AND assignment
Binary
|=
test |= true
OR assignment
Binary
^=
test ^= true
XOR assignment
Binary
Logical NOT Operator (!)
The logical
NOT
operator (
!
) is used in the form
!operand
The operator returns
true
if the
operand
is
false
, and
false
if the
operand
is
true
.
boolean b;
b = !true; // Assigns false to b
b = !false; // Assigns true to b
int i = 10;
int j = 15;
boolean b1 = true;
b = !b1; // Assigns false to b
b = !(i > j); // Assigns true to b, because i > j returns false
Suppose you want to change the value of a
boolean
variable
b
to
true
if its current value is
false
, and to
false
if
its current value is
true
. This can be achieved as shown:
b = !b; // Assigns true to b if it was false and false if it was true
Logical Short-Circuit AND Operator (&&)
The logical short-circuit
AND
operator (
&&
) is used in the form
operand1 && operand2
The operator returns true if both operands are
true
. If either operand is
false
, it returns
false
. It is called a
short-circuit
AND
operator because if
operand1
(the left-hand operand) evaluates to
false
, it returns
false
without
evaluating
operand2
(the right-hand operand).