Sub topic 8
Comparing Primitive Values
A comparison asks a question about two values. For example, is a score high enough, or are two numbers equal? Java answers with a boolean value: either true or false.
A primitive value is a simple value stored directly, such as an int, a double, a char, or a boolean. Comparing these values helps a program make decisions based on numbers, characters, and true-or-false results.
Comparison operators
An operator is a symbol that tells Java to perform an action. An operand is a value the operator acts on. An expression is a combination that produces a result.
In the expression 5 < 7, the operands are 5 and 7. The operator is <, and the result is true.
| Operator | Meaning | Example | Result |
|---|---|---|---|
| `<` | Less than | `5 < 7` | `true` |
| `>` | Greater than | `5 > 7` | `false` |
| `<=` | Less than or equal to | `5 <= 5` | `true` |
| `>=` | Greater than or equal to | `5 >= 7` | `false` |
| `==` | Equal to | `5 == 7` | `false` |
| `!=` | Not equal to | `5 != 7` | `true` |
The first four are called relational operators. They compare the order of numeric values. The last two are equality operators. They check whether values are equal or not equal.
The result of each comparison is a boolean, not a number. For example, 5 < 7 produces true, not 1.
Compare numbers
You can compare numeric values stored in variables as well as numbers written directly in an expression. Consider a passing score of 60:
score >= 60istruewhen the score is 60 or more.score > 60istrueonly when the score is above 60.
The difference matters at the boundary, which is the value where the result changes. At exactly 60, >= produces true, but > produces false. A boundary included by <= or >= is called inclusive.
Here is a complete program that compares several primitive values. Save it in a file named ComparisonDemo.java.
public class ComparisonDemo {
public static void main(String[] args) {
int score = 60;
System.out.println(score >= 60); // true
System.out.println(score > 60); // false
System.out.println(score == 60); // true
System.out.println(score != 60); // false
int temperature = -3;
System.out.println(temperature < 0); // true
System.out.println(temperature >= 0); // false
int whole = 7;
double decimal = 7.0;
System.out.println(whole == decimal); // true
char first = 'A';
char second = 'a';
System.out.println(first < second); // true
System.out.println(first == second); // false
boolean open = true;
boolean ready = false;
System.out.println(open == ready); // false
System.out.println(open != ready); // true
}
}Run it from the folder containing the file:
javac ComparisonDemo.java
java ComparisonDemoThe program prints one result per line. Check each result against the comment beside it.
Work through a comparison
Look at temperature < 0 in the program:
- The variable
temperatureholds-3. - The operator
<asks whether the left value is less than the right value. - Negative three is less than zero, so the expression produces
true.
The next expression, temperature >= 0, asks whether -3 is greater than or equal to zero. Neither is true, so the result is false.
You can store a comparison result in a boolean variable. For example, boolean passing = score >= 60; stores true when score is 60.
Compare different numeric types
A type tells Java what kind of value a variable holds. For example, int holds whole numbers, while double holds numbers that can have fractional parts.
Java allows comparisons between different numeric primitive types. In the program, whole == decimal compares an int with a double. Java converts the int value to a double for the comparison. Both values are then 7.0, so the result is true.
Conversion can matter when a value cannot be represented exactly in the chosen type. For instance, comparing a large int with a float can give a surprising result because the int may be rounded when it is converted to a float. Do not assume that comparing different numeric types always preserves every digit.
Compare characters
A char is a primitive type that stores one UTF-16 code unit, a number used by Java to represent text. A character literal such as 'A' uses single quotes.
Character comparisons use those numeric values. In the example, 'A' < 'a' is true because the value for uppercase A is smaller than the value for lowercase a.
This is not the same as sorting words in a human language. In particular, uppercase and lowercase letters have different values. Use character comparisons when you need to compare the individual values, not when you need language-aware text sorting.
Compare boolean values
You can use == and != with two boolean values:
true == falseisfalse.true != falseistrue.true == trueistrue.
You cannot use <, >, <=, or >= to order boolean values. Java also does not treat 1 as true or 0 as false, so a boolean cannot be compared to a number with ==.
Often, comparing a boolean to true is unnecessary. If open is already a boolean, open itself has the same result as open == true.
Floating-point equality needs care
A floating-point value is a number stored with limited precision, meaning it may not hold every decimal value exactly. Both float and double are floating-point types.
For example, 0.1 + 0.2 == 0.3 produces false in Java. The stored values and the result of the addition are close to the written decimal numbers, but the result is not exactly equal to the stored value for 0.3.
If a calculation only needs to be close enough, compare the size of the difference with a limit chosen for the task. That limit depends on what the numbers measure and how much error is acceptable. For values that must be exact, such as money, consider an exact representation instead of relying on floating-point equality.
There is also a special floating-point value called NaN, meaning “not a number.” A comparison using == is false when either operand is NaN, even when both operands are NaN. Ordered comparisons with NaN are also false; != is true. To test a double value for NaN, use Double.isNaN(value) rather than value == Double.NaN.
Common mistakes
- Choosing the wrong boundary: use
>=rather than>when the boundary itself should pass. - Writing
=instead of==: assignment and equality are different operations. - Comparing a boolean with a number: Java keeps
booleanseparate from numeric types. - Expecting exact decimal results from every floating-point calculation.
- Assuming character order is the same as the order used to sort words.
This chapter covers equality for primitive values. Equality for values that refer to objects, such as strings, follows different rules.
Practice
Exercise
A variable age holds 18. What do age >= 18 and age > 18 produce?
Show answer
age >= 18 produces true; age > 18 produces false. The first comparison includes the boundary.
Exercise
What do true != false and 'A' == 'a' produce?
Show answer
true != false produces true. 'A' == 'a' produces false because the two characters have different numeric values.
Exercise
Why is value == Double.NaN not a reliable way to check whether a double is NaN?
Show answer
Equality with NaN is always false. Use Double.isNaN(value) instead.