In CS131 you worked with simple Boolean expressions
expressions that return a true
or false
value. An example is
if (this.isBesideThing()) { this.pickThing(); }
This code could be from a new Robot
class. It
only picks up a Thing
if the Boolean expression
this.isBesideThing()
returns true
that is, the robot is beside a Thing
.
Just as arithmetic expressions can be combined, so can Boolean expressions. Recall the addition table from grade 2 math. It shows how to combine integers using the plus operation:
+ | 0 | 1 | 2 | 3 |
0 | 0 | 1 | 2 | 3 |
1 | 1 | 2 | 3 | 4 |
2 | 2 | 3 | 4 | 5 |
3 | 3 | 4 | 5 | 6 |
We can form a similar tables for combining Boolean
expressions with the OR (||
in Java) and AND
(&&
) operations:
|
|
Tables are often helpful for convincing yourself that a Boolean expression is correct. For example, you might decide to watch television tonight if the homework due tomorrow is finished and all your remaining homework is due after the weekend or your special friend is visiting. Expressing this as a Java predicate looks like:
public boolean watchTV(boolean tomorrowDone, boolean restNotDue, boolean visitor) { if (tomorrowDone && restNotDue || visitor) { return true; } else { return false; } }
A truth table can be constructed for this problem with the following steps:
![]() |
![]() |
![]() |
![]() |
![]() |
1 | 2 | 3 | 4 | 5 |
tomorrowDone |
restNotDue |
visitor |
1 && 2 |
4 || 3 |
true
and false
in the
first column. Alternate pairs of true
and
false
in the second column. Alternate groups of four
true
s and four false
s in the third
column. This pattern can be extended for any number of boolean
variables. Notice the pattern in the colours in the table,
below.tomorrowDone |
restNotDue |
visitor |
1 && 2 |
4 || visitor |
true | true | true | true | true |
false | true | true | false | true |
true | false | true | false | true |
false | false | true | false | true |
true | true | false | true | true |
false | true | false | false | false |
true | false | false | false | false |
false | false | false | false | false |
Suppose that there was an additional Boolean variable,
scaredOfFailing
and that the Boolean expression was
if ((tomorrowDone && restNotDue || visitor) && !scaredOfFailing)
How many rows would you ADD to the table, above?