Java Reference
In-Depth Information
These assignment statements say, in effect, “Set this boolean variable according
to the truth value returned by the following test.” The first statement sets the variable
test1 to true , because the test evaluates to true . The second sets the variable
test2 to false , because the second test evaluates to false . You don't need to
include parentheses, but they make the statements more readable.
Obviously, then, assignment is one of the operations you can perform on variables
of type boolean .
Logical Operators
In Java, you can form complicated Boolean expressions using what are known as the
logical operators, shown in Table 5.3.
Table 5.3
Logical Operators
Operator
Meaning
Example
Value
AND (conjunction)
&&
(2 == 2) && (3 < 4)
true
OR (disjunction)
||
(1 < 2) || (2 == 3)
true
NOT (negation)
!
!(2 == 2)
false
The NOT operator ( ! ) reverses the truth value of its operand. If an expression eval-
uates to true , its negation evaluates to false , and vice versa. You can express this
relationship in a truth table. The truth table that follows has two columns, one for a
variable and one for its negation. For each value of the variable, the table shows the
corresponding value of the negation.
Truth Table for NOT ( ! )
p
!p
true
false
false
true
In addition to the negation operator, there are two logical connectives you will use,
AND ( && ) and OR ( || ). You use these connectives to tie together two Boolean expres-
sions, creating a new Boolean expression. The following truth table shows that the AND
operator evaluates to true only when both of its individual operands are true .
Truth Table for AND ( && )
p
q
p && q
true
true
true
true
false
false
false
true
false
false
false
false
 
 
Search WWH ::




Custom Search