Java Reference
In-Depth Information
17. public static void main(String [] args) {
18. showGrade(77);
19. showGrade(54);
20. }
21.}
After an
if
expression evaluates to
true
and its corresponding block of code executes,
control leaves the
if-then-else
statement. For example, when
grade
equals
77
, line 7 is
true
and line 8 executes, printing
C
. Line 9 is also
true
, but it is not evaluated because
control jumps out of the
if
statement to line 14.
When
grade
equals
54
, none of the
if
statements are
true
, so the
else
on line 11
executes and an
F
displays. The output of the
Grades
program is
C is your grade
F is your grade
Note that at most one block of code in an
if-then-else
control structure executes. The
last
else
block is always optional. When no else block appears, no block of code executes
if all the
boolean
expressions are
false
. Otherwise, when an
if-then-else
does contain
an ending
else
block, exactly one block of code in the control structure executes: either the
fi rst
if
condition to evaluate to
true
, or the
else
block if all
if
conditions are
false
.
Be Careful with
boolean
Comparisons
Watch out for assignment statements that look like
boolean
expressions. For example,
look at the following code and see if you can determine its output:
12. boolean b = false;
13. if(b = true) {
14. System.out.println(“true”);
15. } else {
16. System.out.println(“false”);
17. }
This code compiles fi ne. On line 13,
b = true
is an assignment, not a comparison. The
result of this
boolean
assignment is the value of
b
after the assignment, which is
true
.
Therefore, the output of this code is
true
Keep an eye out for this type of question on the exam.
Search WWH ::
Custom Search