Next: The while statement. Up: Expressions and loops. Previous: Operators.


Comparisons

Textbook: Section 4.1

Thus far, we've seen operators grouped into four levels of precedence.

unary +, unary -highest precedence
*, /, %
binary +, binary -
=, +=, -=, *=, /=, %=lowest precedence
These operators all work with numeric values and produce numeric values. Today we'll see some boolean operators and see how they can be used to produce our first nontrivial programs.

The operators we'll examine in this section are the comparison operators, which exist for comparing two values together.

Inequality operators

Below the precedence level for addition and subtraction, and above the precedence level for assignment operators, are the inequality operators: <, >, <=, and >=. An inequality operator needs a numeric value on both sides of it, and it computes a boolean value.

For example, you might have the following in a Java program.

double x = 1.3;
double y = 2.1;
boolean is_lessthan = (x < y);
After this is executed, is_lessthan holds the boolean value true, since indeed 1.3 is less than 2.1. (The parentheses in this fragment are optional - the < operator has higher precedence than the assignment operator anyway. But I would include them just to make the program easier to read.)

Equality operators

Java also has operators for comparing two values: == for equality and != for inequality. (Oddly, Java uses the exclamation point to indicate NOT.) They actually fall below the inequality operators in the hierarchy.

unary +, unary -highest precedence
*, /, %
binary +, binary -
<, >, <=, >=
==, !=
=, +=, -=, *=, /=, %=lowest precedence

Notice that Java uses == (two equal signs!) for seeing if two numbers are equal. This operator takes two values and computes whether they are currently equal. This is very different from the assignment operator (one equal sign =), which actually alters the value of the variable named on its left.

Note: You should basically never use the equality operators in conjunction with doubles. The problem is that doubles will have some slight error. For example, if you subtract 1.1 from 1.2, the computer would compute the approximation 0.09999999999999987. So the expression

1.2 - 1.1 == 0.1
would be false! The proper way to do these tests is to see if the absolute value of the difference of the two numbers is small. You'll see how to compute the absolute value later...


Next: The while statement. Up: Expressions and loops. Previous: Operators.