Java Reference
In-Depth Information
One limitation of the relational operators is that they should be used only with
primitive data. Later in this chapter we will talk about how to compare objects for
equality, and in a later chapter we'll discuss how to perform less-than and greater-
than comparisons on objects.
Nested if/else Statements
Many beginners write code that looks like this:
if (<test1>) {
<statement1>;
}
if (<test2>) {
<statement2>;
}
if (<test3>) {
<statement3>;
}
This sequential structure is appropriate if you want to execute any combination of
the three statements. For example, you might write this code in a program for a ques-
tionnaire with three optional parts, any combination of which might be applicable for
a given person.
Figure 4.3 shows the flow of the sequential if code. Notice that it's possible for
the computer to execute none of the controlled statements (if all tests are false), just
one of them (if only one test happens to be true), or more than one of them (if multiple
tests are true).
Often, however, you only want to execute one of a series of statements. In such
cases, it is better to nest the if statements, stacking them one inside another:
if (<test1>) {
<statement1>;
} else {
if (<test2>) {
<statement2>;
} else {
if (<test3>) {
<statement3>;
}
}
}
When you use this construct, you can be sure that the computer will execute at
most one statement: the statement corresponding to the first test that evaluates to
true . If no tests evaluate to true , no statement is executed. If executing at most
 
Search WWH ::




Custom Search