AP® Computer Science A · Unit 2 · Topic 2.2

Boolean Expressions and Relational Operators

A boolean expression is any expression that evaluates to exactly true or false, and relational operators like ==, ≠, <, >, ≤, and ≥ are how you build them by comparing two values.

A computer branches by asking a yes-or-no question, and Java represents that answer as a boolean: true or false, nothing in between. The six relational operators give you ways to ask that question of numbers: == and ≠ test equality and inequality, while <, >, ≤, and ≥ test order. Picture each one splitting the number line into two regions — x > 5 marks everything above 5 as true and everything else false; x ≤ 5 flips which side counts. Whatever condition sits inside an if or a while must boil down to one of these true/false values.

Order of operations matters here just like in arithmetic: Java finishes all the arithmetic before it compares anything. In (q·3 + r) % 3 == 1, Java computes q·3 + r, then takes that result mod 3, and only then compares the leftover to 1. Relational operators always sit at the end of that chain, checking a finished number against another finished number.

This topic sets up everything else in the unit: if-statements choose a branch based on a boolean expression, while and for loops keep running as long as one stays true, and compound conditions in the next topic glue several of these together with && and ||. Get comfortable with what makes an expression boolean now, because every branch and every loop condition after this is built from exactly these pieces.

Key terms

Boolean expression
Any expression that evaluates to exactly one of two values, true or false.
Relational operator
An operator (==, ≠, <, >, ≤, ≥) that compares two values and produces a boolean result.
Assignment operator
The single = symbol, which stores a value into a variable and evaluates to that value's type, not a boolean.
Evaluation order
The sequence in which Java resolves a compound expression, finishing arithmetic before applying any relational comparison.

Watch it explained

  1. How it worksHow do the six relational operators each split the number line into two regions?
  2. Worked exampleFind the value of 7 % 3 == 1 and of 5·2 ≤ 9, showing the evaluation order.
  3. Common mistakeWhy isn't = the operator you use to test whether two values are the same?
  4. Going furtherWhat happens when you compare two doubles with == after doing arithmetic on them?

Check yourself

Your turn1 of 2
In the condition (7·3 + 1) % 3 == 1, arithmetic runs before comparison happens. What does (7·3 + 1) % 3 evaluate to?

End of topic.