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.
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.
boolean variable.Storing the Result of a Comparison
Predict the output.
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);
Can vote: false
Can vote: false
Can vote: true
- 1Line 3. 17 ≥ 18 is
false, and that value is stored incanVote. - 2After
agebecomes 18,canVotestill holdsfalse. The variable stored a value, not a formula. - 3Re-evaluating the comparison with the new age stores
true.
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.
true or false.| Operator | Meaning | Works with | Example (x = 7) |
|---|---|---|---|
== | equal to | Any primitives; references (same object?) | x == 7 is true |
!= | not equal to | Any primitives; references | x != 7 is false |
< | less than | Numeric values | x < 7 is false |
> | greater than | Numeric values | x > 5 is true |
<= | less than or equal to | Numeric values | x <= 7 is true |
>= | greater than or equal to | Numeric values | x >= 8 is false |
Evaluating Comparisons
Predict each value.
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);
true
false
true
true
true
- 1
a < b. 7 < 12:true. - 2
a >= b. 7 ≥ 12:false. - 3
a != b. 7 and 12 differ:true. - 4
a == 7andb <= 12. Bothtrue;<=includes equality.
boolean value.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.
Arithmetic Inside Comparisons
Predict each value.
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);
true
true
false
false
- 1
x * 3 > y. 12 > 9:true. - 2
x + y == 13. 13 == 13:true. - 3
y % x != 1. 9 % 4 = 1, and 1 != 1 isfalse. - 4
y / x >= 2.25. Integer division: 9 / 4 = 2, and 2 ≥ 2.25 isfalse.
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.
Comparing int and double Values
Predict each value.
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);
true
false
true
true
- 1
5 == 5.0. Theintis widened to 5.0 before comparing:true. - 2
7 / 2 == 3.5. 7 / 2 is integer division, 3; 3.0 == 3.5 isfalse. - 3
7 / 2.0 == 3.5. Now the division isdouble: 3.5 == 3.5 istrue. - 4
10 > 9.99. 10.0 > 9.99:true.
int to double when needed, but the arithmetic on each side follows its own type rules first.Why == Is Risky With double
Predict the output.
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);
false
0.30000000000000004
true
- 1Round-off. 0.1 + 0.2 is stored as 0.30000000000000004, which is not the same
doubleas 0.3, so==isfalse. - 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.
double values with == can fail because of round-off; compare the size of the difference instead.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.
== compares the actual values. With reference types, it compares the object references.| Comparison | Primitive types | Reference types |
|---|---|---|
a == b | Are the values the same? | Do both refer to the same object? |
a != b | Are the values different? | Do they refer to different objects? |
| Content equality | Use == | Use a method such as equals |
<, >, <=, >= | Numeric types only | Not allowed (strings use compareTo) |
== and != With Objects
Predict each value.
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));
false
true
true
true
- 1
s == t. Two separate objects created withnew: different references,false. - 2
s == u.uholds the same reference ass:true. - 3
s != t. The references differ:true. - 4
s.equals(t). Same characters:true.
== and != compare object references; use equals to compare the contents of strings.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.
| Mistake | Example | Correct form |
|---|---|---|
| = instead of == | x = 5 | x == 5 |
| Chained comparison | 0 < x < 10 | 0 < x && x < 10 |
| Spaced operator | x < = 5 | x <= 5 |
| Reversed operator | x =< 5 | x <= 5 |
| == on computed doubles | sum == 0.3 | Math.abs(sum - 0.3) < 0.000001 |
= Is Not ==, and Comparisons Do Not Chain
Explain why each statement does not compile.
int x = 4;
boolean same = (x = 5);
int x = 4;
boolean inRange = 0 < x < 10;
- 1
x = 5is assignment, which produces anint, not aboolean. The comparison isx == 5. - 2
0 < x < 10. Java evaluates0 < xfirst, givingtrue, then triestrue < 10, comparing abooleanwith anint, which is not allowed. - 3Fix for a range. Two comparisons joined with the logical operator "and",
0 < x && x < 10, which is the subject of compound Boolean expressions.
== to compare, and write each comparison separately; a range check needs two comparisons joined by a logical operator.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.
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.