Java Reference
In-Depth Information
Relational Operators
Computerscanmakesimpledecisions.Forexample,acomputerprogram
cantakeonepathofactioniftwovariables, a and b ,areequal,anotherpath
if a isgreaterthan b ,andyetanotheroneif b isgreaterthan a .TheJavarela-
tionaloperatorsevaluateifasimplerelationshipbetweenoperandsistrue
orfalse. Table7-2 liststheJavarelationaloperators.
Table 7-2
Java Relational Operators
OPERATOR
ACTION
<
less than
>
greater than
<=
less than or equal to
>=
greater than or equal to
==
equal to
!=
not equal to
The == operator deserves special notice. This operator is used to de-
termine if one operand is equal to the other one. It is unrelated to the as-
signment operator (=) which has already been discussed. In the following
examples we set the value of a boolean variable according to a compari-
son between two numeric variables, x and y .
boolean result;
intx=4;
inty=3;
result=x>y;
//Case 1 - result is true
result=x<y;
//Case 2 - result is false
result=x==0;
//Case 3 - result is false
result=x!=0;
//Case 4 - result is true
result=x<=4;
//Case 5 - result is true
Notice in case 3 the different action of the assignment and the rela-
tional operator. The assignment operator (=) is used in this expression to
assign to the variable result the boolean true or false that results from
comparing x to 0. The comparison is performed by means of the == oper-
ator. The result is false because the value of the variable x is 4. One com-
mon programming mistake is to use the assignment operator in place of
the relational operator, or vice versa. This error is particularly dangerous
because the resulting expression is often a legal one.
 
Search WWH ::




Custom Search