Java Reference
In-Depth Information
No
Yes
Is the test true?
Execute the else
controlled statement(s)
Execute the if
controlled statement(s)
Execute the statement
after the if/else statement
Figure 4.2
Flow of if/else statement
This control structure is unusual in that it has two sets of controlled statements and
two different keywords ( if and else ). Figure 4.2 indicates the flow of control. The
computer performs the test and, depending upon whether the code evaluates to true
or false , executes one or the other group of statements.
As in the case of the for loop, if you have a single statement to execute, you
don't need to include curly braces. However, the Sun convention is to include
the curly braces even if you don't need them, and we follow that convention in
this topic.
Relational Operators
An if/else statement is controlled by a test. Simple tests compare two expressions
to see if they are related in some way. Such tests are themselves expressions of the
following form and return either true or false :
<expression> <relational operator> <expression>
To evaluate a test of this form, first evaluate the two expressions and then see
whether the given relation holds between the value on the left and the value on the
right. If the relation holds, the test evaluates to true . If not, the test evaluates to false .
The relational operators are listed in Table 4.1. Notice that the equality operator
consists of two equals signs ( == ), to distinguish it from the assignment operator ( = ).
Table 4.1
Relational Operators
Operator
Meaning
Example
Value
equal to
==
2 + 2 == 4
true
not equal to
!=
3.2 != 4.1
true
less than
<
4 < 3
false
greater than
>
4 > 3
true
less than or equal to
<=
2 <= 0
false
greater than or equal to
>=
2.4 >= 1.6
true
 
Search WWH ::




Custom Search