Unit 2.5: Compound Boolean Expressions
Logical Operators
Logical operators combine boolean expressions.
Compound Logic
- Logical operators allow you to create complex conditions by joining multiple Boolean expressions. They evaluate to a single
trueorfalseresult.
| Operator | Name | Description |
|---|---|---|
! |
NOT | Inverts the value (!true is false). |
&& |
AND | True only if both operands are true. |
|| |
OR | True if at least one operand is true. |
Truth Tables
| A | B | !A |
A && B |
A || B |
|---|---|---|---|---|
true |
true |
false |
true |
true |
true |
false |
false |
false |
true |
false |
true |
true |
false |
true |
false |
false |
true |
false |
false |
Short-Circuit Evaluation
- AND (
&&): If the first operand isfalse, the result isfalseimmediately. The second operand is not evaluated. - OR (
||): If the first operand istrue, the result istrueimmediately. The second operand is not evaluated.
Examples
Using Logical Operators
Task: Applying compound boolean logic and short-circuit protection.
public class LogicExample {
public static void main(String[] args) {
int age = 15;
boolean hasLicense = false;
// AND example
if (age >= 16 && hasLicense) {
System.out.println("Can drive");
} else {
System.out.println("Cannot drive");
}
// OR example
boolean hasCash = false;
boolean hasCredit = true;
if (hasCash || hasCredit) {
System.out.println("Can pay");
}
// Short-circuit protection against divide by zero
int count = 0;
int total = 100;
// If count is 0, the second part (total / count) is skipped
if (count != 0 && (total / count > 10)) {
System.out.println("Valid average");
} else {
System.out.println("Cannot calculate");
}
}
}