Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^156) | Selection and Encapsulation
Let’s look at each of these possibilities in detail.


booleanVariables and Constants As we have seen, a booleanvariable is a variable declared to be


of type boolean, which can contain either the value trueor the value false. For example, if
dataOKis a booleanvariable, then

dataOK = true;

is a valid assignment statement.

Relational Operators Another way of assigning a value to a booleanvariable is to set it equal to


the result of comparing two expressions with a relational operator. Relational operators test
a relationship between two values.
Let’s look at an example. In the following code fragment,lessThanZerois a booleanvari-
able and iand jare intvariables:

lessThanZero = (i < 0); // Compare i and 0 with the "less than"
// operator, and assign the value to lessThanZero

By comparing two values, we assert that a relationship (such as “less than”) exists be-
tween them. If the relationship does exist, the assertion is true; if not, it is false. We can test
for the following relationships in Java:

Operator Relationship Tested
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
An expression followed by a relational operator followed by an expression is called a re-
lational expression. The result of a relational expression is of type boolean. For example, if xis
5 and yis 10, the following expressions all have the value true:

x != y
y > x
x < y
y >= x
x <= y

If xand yare instead of type char, and xcontains the character 'M'and yholds 'R', the val-
ues of the expressions are still truebecause the relational operator <, when used with let-
ters, means “comes before in the alphabet” or, more properly, “comes before in the collating
Free download pdf