Java Reference
In-Depth Information
Java provides you with six relational operators (see Table 3-1 ) for comparing two data values. The data val-
ues you are comparing can be variables, constants, or expressions with values drawn from Java's primitive
data types — byte, short, int, long, char, float , or double .
TABLE 3-1 : Java Relational Operators
RELATIONAL
OPERATORS
DESCRIPTION
Produces the value true if the left operand is greater than the right operand, and false
otherwise.
>
Produces the value true if the left operand is greater than or equal to the right operand, and
false otherwise.
>=
Produces the value true if the left operand is equal to the right operand, and false other-
wise.
==
Produces the value true if the left operand is not equal to the right operand, and false
otherwise.
!=
Produces the value true if the left operand is less than or equal to the right operand, and
false otherwise.
<=
Produces the value true if the left operand is less than the right operand, and false other-
wise.
<
As you see, each operator produces either the value true or the value false , and so is eminently suited
to the business of making decisions. This also implies that you can use a boolean variable to store the result
of a comparison. You saw how to declare variables of type boolean in the previous chapter. For example,
you could define a boolean variable state and set its value to be the result of an expression using a com-
parison as follows:
boolean state = false; // Define and initialize the variable
state = x - y < a + b; // Store the result of comparing x-y with a+b
The value of the variable state is set to true in the assignment statement if x - y is less than a + b ,
and to false otherwise.
To understand how the preceding expression is evaluated, refer to the precedence table for operators that
I introduced in the last chapter. You can see that the comparison operators are all of lower precedence than
the arithmetic operators, so arithmetic operations are always completed before any comparisons are made,
unless of course there are parentheses dictating otherwise. The expression:
x - y == a + b
produces the result true if x - y is equal to a + b because these arithmetic sub-expressions are evaluated
first, and the values that result are the operands for the == operator. Of course, it is helpful to put the paren-
theses in, even though they are not strictly necessary. It leaves no doubt as to what is happening if you write:
(x - y) == (a + b)
Note that if the left and right operands of a relational operator are of differing types, values are promoted
in the same way as you saw in the previous chapter for mixed arithmetic expressions. So if aDouble is of
type double and number is of type int in the following expression
aDouble < number + 1
 
 
Search WWH ::




Custom Search