Java Reference
In-Depth Information
Is 23 (LHS) less than 45 (RHS)
Left-Hand Side (LHS)
Right-Hand Side (RHS)
23 < 45
Figure 3-1
There are other comparison operators, 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'll 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 operators, such as + , - , * , and / . This
means that if you make a comparison such as 3 * 5 > 2 * 5 , the multiplication calculations are worked
out fi rst, 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 fi nd
yourself surprised by the outcome.
Assignment versus Comparison
One very important point to mention is the ease with which the assignment operator ( = ) and the com-
parison 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 amaz-
ingly easy to put one equals sign where you meant to put two.
Search WWH ::




Custom Search