AP Computer Science A · Study guide

Relational Boolean Expressions

AP® Computer Science A · Selection and Iteration

Boolean Expressions With Relational Operators

How Java compares values with ==, !=, <, >, <=, and >=: what each comparison evaluates to, how precedence and types affect the result, and why comparing objects and doubles needs extra care.

Big Picture

Every decision in a program rests on a question with a true or false answer. In Java, those questions are written as Boolean expressions. Values can be compared using the relational operators == and != to determine whether they are the same; with primitive types this compares the actual values, and with reference types it compares the object references. Numeric values can be compared using <, >, <=, and >=. An expression involving relational operators evaluates to a Boolean value.

1Boolean Values and Expressions

The type boolean has exactly two values, true and false. A Boolean expression is any expression whose value is one of them. The simplest are the literals themselves and boolean variables; the most common are comparisons such as score >= 60, which ask a question about the current values of variables.

A comparison is evaluated like any other expression: Java substitutes the current values, computes the result, and produces a value. That value can be printed, stored in a boolean variable, passed to a method, or, most importantly, used to control a decision or a loop. Storing a comparison captures its value at that moment; if the variables change later, the stored value does not update unless the comparison is evaluated again.

Good names make boolean variables read like yes-or-no questions: isOpen, hasTicket, passed, canVote. When such a variable later controls a decision, the code reads almost like a sentence, which makes the program's logic easier to check. Names such as flag or b, by contrast, hide what the question was.

Figure 1. An expression involving relational operators evaluates to a Boolean value, which can be stored in a boolean variable.
Worked Example 1 boolean variables

Storing the Result of a Comparison

Predict the output.

Code
int age = 17;
int minimum = 18;
boolean canVote = age >= minimum;
System.out.println("Can vote: " + canVote);
age = age + 1;
System.out.println("Can vote: " + canVote);
canVote = age >= minimum;
System.out.println("Can vote: " + canVote);
Output
Can vote: false
Can vote: false
Can vote: true
  1. 1Line 3. 17 ≥ 18 is false, and that value is stored in canVote.
  2. 2After age becomes 18, canVote still holds false. The variable stored a value, not a formula.
  3. 3Re-evaluating the comparison with the new age stores true.
Result: The output is false, false, true. A boolean variable holds the value the comparison had when it was evaluated; it does not update by itself.

2The Relational Operators

Java has six relational operators. == (equal to) and != (not equal to) determine whether two values are the same. <, >, <=, and >= determine the relationship between numeric values: which is smaller, which is larger, or whether they could be equal. The two-character operators are written without a space and in exactly this order: <= and >=, never =<.

Note the difference between = and ==. A single equals sign assigns a value to a variable; a double equals sign compares two values and produces true or false. Mixing them up is one of the most common errors in early programs, and Java usually catches it at compile time.

Each operator has an opposite that gives the reverse answer for every pair of values: == and !=, < and >=, > and <=. Knowing these pairs is useful when a condition needs to be turned around, for example from "the bottle is full" (amount >= capacity) to "the bottle is not full" (amount < capacity). Note that the opposite of < is >=, not >: the boundary value must land on exactly one side.

Figure 2. Relational operators compare two values. Every expression built with them evaluates to a Boolean value, true or false.
OperatorMeaningWorks withExample (x = 7)
==equal toAny primitives; references (same object?)x == 7 is true
!=not equal toAny primitives; referencesx != 7 is false
<less thanNumeric valuesx < 7 is false
>greater thanNumeric valuesx > 5 is true
<=less than or equal toNumeric valuesx <= 7 is true
>=greater than or equal toNumeric valuesx >= 8 is false
Worked Example 2 Relational operators

Evaluating Comparisons

Predict each value.

Code
int a = 7;
int b = 12;
System.out.println(a < b);
System.out.println(a >= b);
System.out.println(a != b);
System.out.println(a == 7);
System.out.println(b <= 12);
Output
true
false
true
true
true
  1. 1a < b. 7 < 12: true.
  2. 2a >= b. 7 ≥ 12: false.
  3. 3a != b. 7 and 12 differ: true.
  4. 4a == 7 and b <= 12. Both true; <= includes equality.
Result: The output is true, false, true, true, true. Each relational expression evaluates to a boolean value.
Common Mistake 1 · Confusing < With <=

score > 60 is false when score is exactly 60; score >= 60 is true. Always ask whether the boundary value itself should satisfy the condition, and choose the operator that includes or excludes it.

3Precedence: Arithmetic Before Comparison

Relational operators have lower precedence than arithmetic operators. In total + 5 >= limit * 2, Java computes total + 5 and limit * 2 first, and only then compares the results. The equality operators == and != come after the ordering operators, and assignment comes last of all, which is why boolean ok = x + 1 > y; computes the comparison before storing it.

Arithmetic inside a comparison follows all of its usual rules, including integer division and the remainder operator. A comparison can only be as accurate as the arithmetic feeding it, so trace each side carefully before comparing.

Parentheses are never wrong when they make an expression clearer. (total + 5) >= (limit * 2) means exactly the same as the version without parentheses, but a reader does not need to recall the precedence rules to understand it. In longer conditions, grouping each side of a comparison this way is a small habit that prevents misreading.

Figure 3. Arithmetic operators are evaluated before relational operators, so each side of a comparison is computed first.
Worked Example 3 Precedence

Arithmetic Inside Comparisons

Predict each value.

Code
int x = 4;
int y = 9;
System.out.println(x * 3 > y);
System.out.println(x + y == 13);
System.out.println(y % x != 1);
System.out.println(y / x >= 2.25);
Output
true
true
false
false
  1. 1x * 3 > y. 12 > 9: true.
  2. 2x + y == 13. 13 == 13: true.
  3. 3y % x != 1. 9 % 4 = 1, and 1 != 1 is false.
  4. 4y / x >= 2.25. Integer division: 9 / 4 = 2, and 2 ≥ 2.25 is false.
Result: The output is true, true, false, false. Arithmetic is evaluated first, with its usual rules, including integer division, and only then is the comparison made.

4Comparing Numeric Types

When an int is compared with a double, the int is widened to a double first, so 5 == 5.0 is true. The arithmetic on each side, however, still follows its own types: 7 / 2 == 3.5 is false because 7 / 2 is computed as integer division and gives 3.

Comparing computed double values with == is risky because of round-off error. 0.1 + 0.2 == 0.3 is false. When two double values only need to be close, compare the size of their difference with a small tolerance: Math.abs(a - b) < 0.000001. Comparisons with < and > are usually safe, except when the values are nearly equal.

Worked Example 4 Mixed types

Comparing int and double Values

Predict each value.

Code
System.out.println(5 == 5.0);
System.out.println(7 / 2 == 3.5);
System.out.println(7 / 2.0 == 3.5);
System.out.println(10 > 9.99);
Output
true
false
true
true
  1. 15 == 5.0. The int is widened to 5.0 before comparing: true.
  2. 27 / 2 == 3.5. 7 / 2 is integer division, 3; 3.0 == 3.5 is false.
  3. 37 / 2.0 == 3.5. Now the division is double: 3.5 == 3.5 is true.
  4. 410 > 9.99. 10.0 > 9.99: true.
Result: The results are true, false, true, true. Numeric comparisons widen int to double when needed, but the arithmetic on each side follows its own type rules first.
Worked Example 5 Comparing doubles

Why == Is Risky With double

Predict the output.

Code
double sum = 0.1 + 0.2;
System.out.println(sum == 0.3);
System.out.println(sum);
System.out.println(Math.abs(sum - 0.3) < 0.000001);
Output
false
0.30000000000000004
true
  1. 1Round-off. 0.1 + 0.2 is stored as 0.30000000000000004, which is not the same double as 0.3, so == is false.
  2. 2A tolerance test. Asking whether the difference is smaller than a tiny amount, here 0.000001, treats values that are "close enough" as equal: true.
Result: The output is false, 0.30000000000000004, and true. Comparing computed double values with == can fail because of round-off; compare the size of the difference instead.
Common Mistake 2 · Using == on Computed doubles

A double that results from arithmetic may differ from the expected value in its last digits. == then reports false even though the values print almost identically. Test whether the difference is within a small tolerance instead.

5Comparing References

With reference types, == and != compare the object references, not the contents of the objects. Two variables are == only when they refer to the very same object. Two separately created objects with identical contents are not ==.

To compare contents, use a method designed for it. For strings, equals compares the characters. The operators <, >, <=, and >= cannot be used with objects at all; strings are ordered with compareTo, whose result can then be compared with 0, as in a.compareTo(b) < 0.

One reference comparison is especially common: checking for null. word != null is true when word refers to an actual object and false when it refers to nothing. Because this compares references, == and != are exactly the right tools, and the check is often made before calling a method through a variable that might be null.

Figure 4. With primitive types, == compares the actual values. With reference types, it compares the object references.
ComparisonPrimitive typesReference types
a == bAre the values the same?Do both refer to the same object?
a != bAre the values different?Do they refer to different objects?
Content equalityUse ==Use a method such as equals
<, >, <=, >=Numeric types onlyNot allowed (strings use compareTo)
Worked Example 6 References

== and != With Objects

Predict each value.

Code
String s = new String("kiwi");
String t = new String("kiwi");
String u = s;
System.out.println(s == t);
System.out.println(s == u);
System.out.println(s != t);
System.out.println(s.equals(t));
Output
false
true
true
true
  1. 1s == t. Two separate objects created with new: different references, false.
  2. 2s == u. u holds the same reference as s: true.
  3. 3s != t. The references differ: true.
  4. 4s.equals(t). Same characters: true.
Result: The results are false, true, true, true. With reference types, == and != compare object references; use equals to compare the contents of strings.
Common Mistake 3 · Comparing String Contents With ==

name == "Lima" asks whether name refers to a particular object, not whether it contains the characters "Lima". It can be false even when the text matches. Use name.equals("Lima").

6Common Errors

Several errors with relational operators are caught by the compiler. Using = where == is intended produces a value of the wrong type. Writing a mathematical range such as 0 < x < 10 fails because Java evaluates 0 < x first and then tries to compare a boolean with a number. A range needs two separate comparisons joined by a logical operator.

Other errors compile but give wrong answers: choosing < when the boundary should be included, comparing computed doubles with ==, or comparing strings with ==. These are logic errors, and the only defense is careful reasoning about what each comparison actually asks.

A reliable way to check a comparison is to test three values: one just below the boundary, the boundary itself, and one just above it. For score >= 60, try 59, 60, and 61 and confirm the results are false, true, and true. Most comparison mistakes show up at exactly one of these three values.

MistakeExampleCorrect form
= instead of ==x = 5x == 5
Chained comparison0 < x < 100 < x && x < 10
Spaced operatorx < = 5x <= 5
Reversed operatorx =< 5x <= 5
== on computed doublessum == 0.3Math.abs(sum - 0.3) < 0.000001
Worked Example 7 Common errors

= Is Not ==, and Comparisons Do Not Chain

Explain why each statement does not compile.

Using = instead of ==
int x = 4;
boolean same = (x = 5);
Chaining two comparisons
int x = 4;
boolean inRange = 0 < x < 10;
  1. 1x = 5 is assignment, which produces an int, not a boolean. The comparison is x == 5.
  2. 20 < x < 10. Java evaluates 0 < x first, giving true, then tries true < 10, comparing a boolean with an int, which is not allowed.
  3. 3Fix for a range. Two comparisons joined with the logical operator "and", 0 < x && x < 10, which is the subject of compound Boolean expressions.
Result: Both statements fail to compile. Use == to compare, and write each comparison separately; a range check needs two comparisons joined by a logical operator.
Common Mistake 4 · Comparing a boolean With true

done == true works but is redundant: done is already true or false. Write the variable itself where a Boolean expression is needed. Redundant comparisons make code harder to read and invite mistakes such as done = true.

Four Habits for Comparisons

1. == Compares, = Assigns

Double-check every equals sign.

2. Check the Boundary

Decide whether the edge value belongs: < or <=.

3. Doubles Need Tolerance

Compare Math.abs(a - b) with a small number.

4. Objects: == Means Same Object

Use equals for string contents.

Core Synthesis

Values can be compared using the relational operators == and != to determine whether the values are the same; with primitive types this compares the actual primitive values, and with reference types it compares the object references. Numeric values can be compared using the relational operators <, >, <=, and >= to determine the relationship between the values. An expression involving relational operators evaluates to a Boolean value.