Java Data and Operators
2. Boolean Data and Operators
2.1. Boolean (or Logical) Operations
Data and operations
Like all the other simple data types, the boolean type consists of certain data - the values true and false - and certain actions or operations that can be performed on those data. For the boolean type there are four basic operations:
AND (&&
), OR (||
), EXCLUSIVE-OR (^
), and NOT (!
). These are defined in the truth
table shown in Table 5.1. A truth tables defines boolean operators by giving their values in all possible situations. The first two columns of the table give possible boolean values for two operands, o1 and o2. An operand is
a value used in an operation. Note that each row gives a different value assignment to the two operands, so that all possible assignments are represented. The remaining columns give the values that result for the various operators given the assignment
of values to o1 and o2.
TABLE 5.1 Truth-table definitions of the boolean operators: AND (&&
), OR (||
), EXCLUSIVE-OR (^
), and NOT (!
)
o1 | o2 | o1 && o2 |
o1 || o2 |
o1 ^ o2 |
!o1 |
---|---|---|---|---|---|
true |
true | true | true | false | false |
true | false | false | true | true | false |
false | true | false | true | true | true |
false | false | false | false | false | true |
Binary operator
To see how to read this table, let's look at the AND operation, which is defined in column 3. The AND operator is a binary operator - that is, it Binary operator requires two operands, o1 and o2. If both o1 and o2 are true, then (o1 &&
o2
) is true (row1). If either o1 or o2 or both o1 and o2 are false, then the expression (o1 && o2) is false (rows 2 and 3). The only case in which (o1
&& o2
) is true is when both o1 and o2 are true (row 4).
The boolean OR operation (column 4 of Table 5.1) is also a binary operation. If both o1 and o2 are false, then (o1 || o2
) is false (row 4). If either o1 or
o2 or both o1 and o2 are true, then the expression (o1 || o2
) is true (rows 1-3). Thus, the only case in which (o1 || o2
) is false is when both o1 and o2 are false.
The boolean EXCLUSIVE-OR operation (column 5 of Table 5.1) is a binary operation, which differs from the OR operator in that it is true when either o1 or o2 is true (rows 2 and 3), but it is false when both o1 and o2 are true (row 1).
Unary operator
The NOT operation (the last column of Table 5.1) is a unary operator - it takes only one operand - and it simply reverses the truth value of its operand. Thus, if o1 is true, !o1 is false, and vice versa.