ACSA Exam Prep
Unit 2 · Selection and Iteration · Topic 2.2

Boolean Expressions

Skill 3.A

Big idea: A Boolean expression is a question with a true/false answer, such as "is x greater than 10?". Relational operators build them.

Learning objectives
  • Develop code to create Boolean expressions with relational operators and determine the result of these expressions.

Relational operators

OperatorMeaningExample (x is 7)Result
==equal tox == 7true
!=not equal tox != 7false
<less thanx < 7false
<=less than or equalx <= 7true
>greater thanx > 3true
>=greater than or equalx >= 8false
Code
int x = 7;
boolean big = x > 5;
System.out.println(big);
System.out.println(x % 2 == 0);
System.out.println(x / 2 == 3);
Output
true
false
true

Comparing primitives vs. references

For primitives, == compares values. For references, == asks whether both variables refer to the same object. That's why Strings and other objects should be compared with equals.

Code
String a = new String("hi");
String b = new String("hi");
String c = a;
System.out.println(a == b);
System.out.println(a == c);
System.out.println(a.equals(b));
Output
false
true
true
Key points
  • Relational operators: == != < <= > >=. Each produces a boolean.
  • == on primitives compares values; on references it compares object references.
Watch out
  • = assigns; == compares.
  • == on two String objects checks whether they are the same object, not the same text.
Quick check
What is 10 % 3 == 1?
Show answer
true. 10 % 3 is 1.