Unit 2 · 14 min

2.2 Boolean Expressions

A relational operator turns two values into one answer: true or false.

Summary, objectives and course and exam description (CED) codes

A Boolean expression built with relational operators evaluates to a Boolean value, true or false. The operators <, >, <= and >= compare numeric values, while == and != check whether two values are the same. With primitive types, == compares the actual values; with reference types, it compares the object references.

By the end of this session you can

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

2.2.A2.2.A.12.2.A.22.2.A.3

Reviewed against the CED on

Know this already? Jump to the checkpoint.

1LearnThe notes, the traps and how to remember them

1. Relational operators produce true or false

A relational operator compares two values. An expression that uses one evaluates to a Boolean value, true or false 2.2.A.3. You can print that value or store it in a boolean variable.

Operator Meaning Example Value
== equal to 4 == 4 true
!= not equal to 4 != 4 false
< less than 3 < 8 true
> greater than 3 > 8 false
<= less than or equal to 5 <= 5 true
>= greater than or equal to 2 >= 7 false
int age = 16;
boolean canDrive = age >= 16;
boolean canVote = age >= 18;
System.out.println(canDrive);
System.out.println(canVote);
System.out.println(age != 16);

Output:

true
false
false

Watch out: =<, => and <> are not Java operators. The equals sign always comes second.

2. Comparing numbers with <, >, <= and >=

The operators <, >, <= and >= compare numeric values to find their relationship 2.2.A.2. They work with int and double values, and you can mix the two types: Java widens the int to a double before comparing.

The arithmetic on each side happens first, with the normal Java rules. That makes integer division a classic trap:

int goals = 7;
int games = 2;
System.out.println(goals / games > 3);
System.out.println(goals / games >= 3);
System.out.println((double) goals / games > 3);

Output:

false
true
true

goals / games is 7 / 2, which is 3 in integer division, and 3 > 3 is false. Casting one operand to double gives 3.5, and 3.5 > 3 is true.

Watch out: a range such as “between 0 and 10” cannot be written as 0 < x < 10 in Java. The first comparison gives a boolean, and a boolean cannot be compared with a number.

int x = 5;
boolean inRange = 0 < x < 10;
error: bad operand types for binary operator '<'

You will join two comparisons with && in Topic 2.5.

3. == and != with primitive values

The operators == and != check whether two values are the same 2.2.A.1. With primitive types (int, double, boolean), they compare the actual primitive values.

int lives = 3;
int startLives = 3;
boolean gameOver = false;
System.out.println(lives == startLives);
System.out.println(lives != 0);
System.out.println(gameOver == false);

Output:

true
true
true

Watch out (= versus ==): one equals sign is assignment, two are comparison. Using = where Java expects a Boolean expression is a compile error for int values:

int lives = 3;
if (lives = 0) {
    System.out.println("Game over");
}
error: incompatible types: int cannot be converted to boolean

Watch out (double values): round-off error can make two values that should be equal compare as different.

double total = 0.1 + 0.2;
System.out.println(total == 0.3);
System.out.println(total);

Output:

false
0.30000000000000004

4. == and != with reference types

With reference types, == and != compare the object references, not the contents of the objects 2.2.A.1. A reference tells Java where an object is. Two references are == only when they refer to the same object.

String a = new String("goal");
String b = new String("goal");
String c = a;
System.out.println(a == b);
System.out.println(a == c);
System.out.println(a.equals(b));

Output:

false
true
true
  • a == b is false: new created two separate objects, even though both hold the letters “goal”.
  • a == c is true: c holds a copy of the reference in a, so both refer to the same object.
  • a.equals(b) is true: equals compares the characters.

Watch out: this is the most common String trap on the AP® exam. To ask “do these strings have the same characters?”, use equals, never ==. Topic 2.6 goes deeper into comparing object references.

5. Store the result and reuse it

Because a relational expression evaluates to a Boolean value, you can store the result in a boolean variable with a clear name. This makes later code easier to read.

double temperature = 38.4;
boolean hasFever = temperature >= 38.0;
System.out.println("Fever: " + hasFever);

Output:

Fever: true

Read hasFever = temperature >= 38.0 from right to left: first the comparison gives true, then = stores true in hasFever.

Lock it in: memory hooks

  • = versus ==One equals sign gives, two equals signs ask.
  • Not equal!= reads as "is not equal to": the exclamation mark means not.
  • <= and >=The equals sign always comes second, the way you say it: less than or equal.

Common misconceptions

  • "= and == do the same thing."

    Not quite. = is assignment: it stores a value. == is a relational operator: it compares two values and gives true or false. if (x = 5) does not compile in Java.

  • "== checks whether two strings have the same letters."

    Not quite. With reference types, == compares the object references, so it asks whether both variables refer to the very same object. Use equals to compare the characters.

  • "7 / 2 > 3 is true because 7 divided by 2 is 3.5."

    Not quite. 7 / 2 is integer division, so it gives 3, and 3 > 3 is false. The arithmetic happens before the comparison, with the usual Java rules.

Exam traps

  • if (score = 100) is a compile error. Comparison needs ==.
  • Integer division inside a comparison: 9 / 2 >= 4.5 is false, because 9 / 2 is 4.
  • Two String objects with the same letters can still be != each other. Compare the contents with equals.
  • Comparing double values with == can fail because of round-off: 0.1 + 0.2 == 0.3 is false.

2PracticeRecall it, then check yourself

In 30 seconds

  1. Relational operators: == != < > <= >=. Every relational expression evaluates to true or false.
  2. <, >, <= and >= compare numeric values.
  3. == and != with primitive values compare the values themselves.
  4. == and != with references compare the references (same object or not), not the contents.
  5. Arithmetic runs before the comparison, so integer division and round-off error affect the result.

Cover this list, say the points out loud, then take the checkpoint without scrolling back up.

Checkpoint · 5 questions

Checkpoint: Boolean Expressions

Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.

  1. 1 Consider the following code segment. What is printed as a result of executing the code segment? 2.2.A.2, 2.2.A.3
    int a = 17;
    int b = 5;
    System.out.println((a / b >= 3.4) + " " + (a % b == 2));
    Show answer

    Answer: A. a / b is integer division, so it is 3, and 3 >= 3.4 is false. a % b is the remainder 2, so a % b == 2 is true. Choosing true for the first comparison treats 17 / 5 as 3.4, which only happens with a double operand.

  2. 2 Consider the following code segment. What is printed as a result of executing the code segment? 2.2.A.1
    String s1 = new String("go");
    String s2 = new String("go");
    String s3 = s1;
    System.out.println((s1 == s2) + " " + (s1 == s3) + " " + s1.equals(s2));
    Show answer

    Answer: D. With reference types, == compares object references. s1 and s2 refer to two separate objects, so s1 == s2 is false; s3 holds the same reference as s1, so s1 == s3 is true. equals compares the characters, so s1.equals(s2) is true. "true true true" wrongly assumes == compares the characters.

  3. 3 The int variable score has been declared and initialized. Which of the following statements compiles and stores true in top exactly when score is 90 or more? 2.2.A.2, 2.2.A.3
    Show answer

    Answer: B. >= is the relational operator for "greater than or equal to", and the comparison evaluates to a Boolean value that can be stored. => is not a Java operator, and score = 90 is an assignment that gives an int, so neither compiles. score > 90 compiles but is false when score is exactly 90.

  4. 4 Consider the following code segment. What is printed as a result of executing the code segment? 2.2.A.1, 2.2.A.3
    double price = 0.1 * 3;
    System.out.println(price == 0.3);
    Show answer

    Answer: D. == compares the two primitive double values exactly. Because of round-off error, 0.1 * 3 is stored as 0.30000000000000004, which is not equal to 0.3, so the expression is false. The code compiles, and println prints the Boolean value, not 0.3.

  5. 5 Consider the following code segment. Which of the following best describes the result of compiling and running it? 2.2.A.1, 2.2.A.3
    int lives = 2;
    if (lives = 0) {
        System.out.println("Game over");
    }
    Show answer

    Answer: B. lives = 0 is an assignment, and its value is the int 0. An if condition must be a Boolean expression, so the compiler reports that an int cannot be converted to boolean. Nothing runs, so the program cannot print or throw anything. The intended comparison is lives == 0.

3PrevailLock it in for exam day

By the numbers

Name each list from memory, then reveal it to check. Each list shows how many items to recall.

  • Relational operators in Java six operators CED 2.2.A.1, 2.2.A.2
    1. == equal to
    2. != not equal to
    3. < less than
    4. > greater than
    5. <= less than or equal to
    6. >= greater than or equal to
  • What == and != compare two cases CED 2.2.A.1
    1. primitive typesthe actual primitive values
    2. reference typesthe object references

Key terms: flip the cards

Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.

  • Boolean expressiontap to flip

    An expression that evaluates to a Boolean value, true or false, such as a comparison with a relational operator or a combination with logical operators.

    Example and CED codes
  • Relational operatorstap to flip

    The operators ==, !=, <, >, <= and >=, which compare two values and evaluate to a Boolean value.

    Example and CED codes
  • Primitive typetap to flip

    A data type for numbers and Boolean values whose variables hold the value directly. In this course: int, double and boolean.

    Example and CED codes
  • Reference typetap to flip

    A data type used to define objects, that is, anything that is not a primitive type. Every class defines a reference type.

    Example and CED codes
  • Reference equality (== versus equals)tap to flip

    Using == or != on object references checks whether they refer to the same object. A class's equals method checks whether two objects are equivalent.

    Example and CED codes
  • Stringtap to flip

    A class whose objects hold a sequence of characters. String is a reference type in java.lang, and String objects are immutable.

    Example and CED codes

Questions students ask

What is a Boolean expression in Java?

An expression that evaluates to a Boolean value, true or false. Expressions built with relational operators such as x > 10 or name != null are Boolean expressions.

What are the relational operators in AP® Computer Science A?

== (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to) and >= (greater than or equal to).

Why does == not work for comparing strings?

String is a reference type, so == compares the references, not the characters. Two different String objects with the same characters are not ==. Use the equals method to compare the characters.

Can I write 0 < x < 10 in Java?

No. 0 < x gives a boolean, and Java cannot compare a boolean with 10, so the code does not compile. Write two comparisons joined with && (Topic 2.5).

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure