1.6

Boolean Expressions

AP Computer Science A

Relational operators

Using relational operators

java
int age = 17;
boolean canVote = age >= 18;     // canVote = false
boolean isTeenager = age >= 13 && age <= 19;  // true (compound boolean — Unit 3)

double gpa = 3.5;
boolean honors = gpa >= 3.7;     // honors = false

int x = 10;
int y = 10;
boolean same = x == y;           // same = true
boolean different = x != y;      // different = false

Boolean variables

java
boolean isRaining = true;
boolean hasMoney = false;

// You can also compute them
int temperature = 85;
boolean isHot = temperature > 80;  // isHot = true

// Use directly in output
System.out.println("Is it hot? " + isHot);  // "Is it hot? true"

The dangerous == vs =

java
int x = 5;

// COMPARISON (returns true or false)
boolean result = (x == 5);   // result = true

// ASSIGNMENT (changes the value of x)
x = 10;   // x is now 10

Comparing with doubles — be careful!

java
double a = 0.1 + 0.2;
double b = 0.3;
System.out.println(a == b);  // might print false!

Building expressions step by step

java
int x = 7;
int y = 3;
int z = 7;

System.out.println(x == y);    // false (7 == 3)
System.out.println(x == z);    // true (7 == 7)
System.out.println(x != y);    // true (7 != 3)
System.out.println(x > y);     // true (7 > 3)
System.out.println(x < y);     // false (7 < 3)
System.out.println(x >= z);    // true (7 >= 7)
System.out.println(y <= x);    // true (3 <= 7)

Boolean expressions in context

java
// In if statements
if (score >= 90) {
    System.out.println("A");
}

// In while loops
while (count < 10) {
    count++;
}

// In for loops
for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

AP Exam Tips

Common Mistakes

Key Vocabulary