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 == 5true
!= not equal to 5 != 2true
< less than 3 < 9true
<= less than or equal 3 <= 3true
> greater than 10 > 4true
>= greater than or equal 10 >= 11false

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

  1. What values can a boolean expression evaluate to?
  2. What is the difference between && and ||?
  3. What does ! do?
  4. Evaluate: (3 < 5) && (2 == 3)
  5. Why can short-circuiting prevent errors?

← Back to Unit 2 topics