Java Reference
In-Depth Information
side (LHS) and a right‐hand side
(RHS), and the comparison is made
between the two. The technical terms
for these are the left operand and the
right operand . For example, the less‐
than operator, with the symbol < , is a
comparison operator. You could write
23 < 45 , which translates as “Is 23 less
than 45?” Here, the answer would be
true (see Figure 3-1).
Is 23 (LHS) less than 45 (RHS)
Left-Hand Side (LHS)
Right-Hand Side (RHS)
23 < 45
figure 3-1  
Other comparison operators exist, the more useful of which are summarized in the following table:
operator sYmbol
purpose
Tests if LHS is equal to RHS
==
Tests if LHS is less than RHS
<
Tests if LHS is greater than RHS
>
Tests if LHS is less than or equal to RHS
<=
Tests if LHS is greater than or equal to RHS
>=
Tests if LHS is not equal to RHS
!=
You see these comparison operators in use in the next section when you look at the if statement.
precedence
Recall from Chapter 2 that operators have an order of precedence. This applies also to the
comparison operators. The == and != comparison operators have the lowest order of precedence,
and the rest of the comparison operators, < , > , <= , and >= , have an equal precedence.
All of these comparison operators have a precedence that is below arithmetic operators, such
as + , , * , and / . This means that if you make a comparison such as 3 * 5 > 2 * 5 , the
multiplication calculations are worked out first, before their results are compared. However,
in these circumstances, it's both safer and clearer if you wrap the calculations on either side
inside parentheses; for example, (3 * 5) > (2 * 5) . As a general rule, it's a good idea to use
parentheses to ensure that the precedence is clear, or you may find yourself surprised by the
outcome.
assignment versus Comparison
One very important point to mention is the ease with which the assignment operator ( = ) and the
comparison operator ( == ) can be mixed up. Remember that the = operator assigns a value to a
variable and that the == operator compares the value of two variables. Even when you have this idea
clear, it's amazingly easy to put one equals sign where you meant to put two.
 
Search WWH ::




Custom Search