Java Reference
In-Depth Information
Is the else clause matched to the inner if statement or the outer if
statement? The indentation in this example implies that it is part of
the inner if statement, and that is correct. An else clause is always
matched to the closest unmatched if that preceded it. However, if
we're not careful, we can easily mismatch it in our mind and mis-
align the indentation. This is another reason why accurate, consistent indentation
is crucial.
Braces can be used to specify the if statement to which an else clause belongs.
For example, if the previous example should have been structured so that the
string "Bravo!" is printed if code is not equal to 'R' , we could force that relation-
ship (and properly indent) as follows:
KEY CONCEPT
In a nested if statement, an else
clause is matched to the closest
unmatched if .
if (code == 'R')
{
if (height <= 20)
System.out.println ("Situation Normal");
}
else
System.out.println ("Bravo!");
By using the block statement in the first if statement, we establish that the else
clause belongs to it.
SELF-REVIEW QUESTIONS (see answers in Appendix N)
SR 5.8
What output is produced by the following code fragment given the
assumptions below?
if (num1 < num2)
System.out.print (" red ");
if ((num1 + 5) < num2)
System.out.print (" white ");
else
System.out.print (" blue ");
System.out.println (" yellow ");
a. Assuming the value of num1 is 2 and the value of num2 is 10?
b. Assuming the value of num1 is 10 and the value of num2 is 2?
c. Assuming the value of num1 is 2 and the value of num2 is 2?
SR 5.9 How do block statements help us in the construction of conditionals?
SR 5.10 What is a nested if statement?
SR 5.11 For each assumption, what output is produced by the following code
fragment?
 
Search WWH ::




Custom Search