Topic 2.2 — Boolean Expressions
Goal: write and evaluate boolean expressions using comparison operators and logical operators, and trace code that depends on true/false conditions.
The big idea
A boolean expression is an expression that evaluates to true or false.
Boolean expressions control selection (if/else) and repetition (loops).
If you can evaluate booleans correctly, you can predict what code will do.
Two types of building blocks
- Comparisons: compare values (like
x < y) - Logic: combine booleans (
&&,||,!)
Comparison operators
These compare two values and produce a boolean.
| Operator | Meaning | Example |
|---|---|---|
== |
equal to | 5 == 5 → true |
!= |
not equal to | 5 != 2 → true |
< |
less than | 3 < 9 → true |
<= |
less than or equal | 3 <= 3 → true |
> |
greater than | 10 > 4 → true |
>= |
greater than or equal | 10 >= 11 → false |
Logical operators
These combine or flip boolean values.
| Operator | Name | Meaning |
|---|---|---|
&& |
AND | true only if BOTH sides are true |
|| |
OR | true if EITHER side is true |
! |
NOT | flips true ↔ false |
Truth table basics
// AND (&&)
T && T -> T
T && F -> F
F && T -> F
F && F -> F
// OR (||)
T || T -> T
T || F -> T
F || T -> T
F || F -> F
Short-circuit evaluation (important)
Java may stop early:
- For
&&, if the left side is false, Java won’t evaluate the right side. - For
||, if the left side is true, Java won’t evaluate the right side.
// If x is 0, this avoids dividing by 0 because the right side won't run:
(x != 0) && (10 / x > 2)
Common mistake: confusing = and ==
=is assignment (sets a variable)==is comparison (checks equality)
int x = 5; // assignment
boolean b = (x == 5); // comparison
Exam mindset
- Evaluate from left to right, using precedence:
!then&&then||. - Use parentheses if it helps you reason:
(a && b) || c. - Remember short-circuiting can matter when the right side has risks (like divide by zero).
Quick self-check
- What values can a boolean expression evaluate to?
- What is the difference between
&&and||? - What does
!do? - Evaluate:
(3 < 5) && (2 == 3) - Why can short-circuiting prevent errors?