Sub topic 9
Combining Boolean Expressions
A Boolean value is either true or false. A Boolean expression is code that produces one of those values. For example, age >= 18 is true when age is at least 18.
You can combine Boolean expressions to describe more than one condition. A condition is a test that is either true or false.
AND, OR, and NOT
An operator is a symbol that performs an action on one or more values. An operand is a value or expression that an operator acts on.
Java has three common Boolean operators:
&&means AND. The result istrueonly when both operands aretrue.||means OR. The result istruewhen at least one operand istrue. It is alsotruewhen both aretrue.!means NOT. It changestruetofalse, andfalsetotrue.
This table shows every combination of two Boolean values, A and B:
| A | B | A && B | A \ | \ | B | !A |
|---|---|---|---|---|---|---|
| false | false | false | false | true | ||
| false | true | false | true | true | ||
| true | false | false | true | false | ||
| true | true | true | true | false |
For example, true && false is false because both values are not true. But true || false is true because one value is true.
Worked example: entry rules
Suppose a visitor needs a ticket. They must also be at least 18 years old or be with an adult.
Save this program as EntryRules.java, then compile and run it:
public class EntryRules {
public static void main(String[] args) {
int age = 16;
boolean hasTicket = true;
boolean withAdult = true;
boolean mayEnter = hasTicket && (age >= 18 || withAdult);
boolean mustWait = !mayEnter;
System.out.println("May enter: " + mayEnter);
System.out.println("Must wait: " + mustWait);
}
}The output is:
May enter: true
Must wait: falseFollow the conditions step by step:
age >= 18isfalsebecause the visitor is 16.withAdultistrue, so(age >= 18 || withAdult)istrue.hasTicketistrue. Both sides of&&are therefore true, somayEnteristrue.!mayEnterchangestruetofalse, somustWaitisfalse.
The parentheses make the age-or-adult choice a group. The ticket is required as well as that choice.
Try changing hasTicket to false and running the program again. Even though the visitor is with an adult, mayEnter becomes false.
Practice
Exercise
If A is true and B is false, what are the results of A && B, A || B, and !A?
Show answer
A && B is false, A || B is true, and !A is false.
Exercise
In the entry program, can a 16-year-old with a ticket but without an adult enter?
Show answer
No. The ticket condition is true, but both age >= 18 and withAdult are false.