Experiment 4: Relational Expressions


In addition to the arithmetic operators,Java provides a variety of other operators. Six of these allow two values to be compared, and produce a boolean (i.e. true/false) value indicating their relationship.

==

equality, returns true if and only if its operands are equal

!=

inequality, returns true if and only if its operands are different

<

less-than, returns true if and only if its left operand is less-than its right operand

>

greater-than, returns true if and only if its left operand is greater-than its right operand

<=

less-than-or-equal-to, returns true if and only if its left operand is not greater than its right operand

<=

greater-than-or-equal-to, returns true if and only if its left operand is not less than its right operand

In Java, a true/false value is represented by the boolean type, so these operators produce a boolean value. Since they are used to identify the relationship between two values, they are called the relational operators.

Assuming that i is 11 and j is 22, complete the following table. In the middle column, use the descriptions above to predict the results of each comparison. Then modify Express.java to display the result of each comparison, and record those results in the rightmost column. (You will need to parenthesize the relational expression within the output statement in order for it to work correctly.)

Comparison

Prediction

Observation

Comparison

Prediction

Observation

i == j

 

 

i != j

 

 

i < j

 

 

i >= j

 

 

i > j

 

 

i <= j

 

 

The relational operators can be used to compare two double (i.e., real) values. However, real equality comparisons should be used with caution, since the machine representation of real numbers may be inexact.

From this exercise, you should now know how to compare two values and determine their relationship.


Back to the Exercise List

Forward to the Next Experiment


Back to the Table of Contents

Back to the Introduction


Copyright 2000 by Prentice Hall. All rights reserved.