Java Reference
In-Depth Information
If the
boolean-expression
evaluates to
true
, the statement(s) for the true case are
executed; otherwise, the statement(s) for the false case are executed. For example, consider
the following code:
if
(radius >=
0
) {
area = radius * radius * PI;
System.out.println(
"The area for the circle of radius "
+
radius +
" is "
+ area);
}
else
{
System.out.println(
"Negative input"
);
}
two-way
if-else
statement
If
radius >= 0
is
true
,
area
is computed and displayed; if it is
false
, the message
"Negative input"
is displayed.
As usual, the braces can be omitted if there is only one statement within them. The braces
enclosing the
System.out.println("Negative input")
statement can therefore be
omitted in the preceding example.
Here is another example of using the
if-else
statement. The example checks whether a
number is even or odd, as follows:
if
(number %
2
==
0
)
System.out.println(number +
" is even."
);
else
System.out.println(number +
" is odd."
);
3.6
✓
✓
Write an
if
statement that increases
pay
by 3% if
score
is greater than
90
, other-
wise increases
pay
by 1%.
Check
Point
3.7
What is the output of the code in (a) and (b) if
number
is
30
? What if
number
is
35
?
if
(number %
2
==
0
)
System.out.println(number +
" is even."
);
if
(number %
2
==
0
)
System.out.println(number +
" is even."
);
else
System.out.println(number +
" is odd."
);
(b)
System.out.println(number +
" is odd."
);
(a)
An
if
statement can be inside another
if
statement to form a nested
if
statement.
The statement in an
if
or
if-else
statement can be any legal Java statement, including
another
if
or
if-else
statement. The inner
if
statement is said to be
nested
inside the outer
if
statement. The inner
if
statement can contain another
if
statement; in fact, there is no
limit to the depth of the nesting. For example, the following is a nested
if
statement:
Key
Point
nested
if
statement
if
(i > k) {
if
(j > k)
System.out.println(
"i and j are greater than k"
);
}
else
System.out.println(
"i is less than or equal to k"
);
The
if (j > k)
statement is nested inside the
if (i > k)
statement.
The nested
if
statement can be used to implement multiple alternatives. The statement
given in Figure 3.3a, for instance, prints a letter grade according to the score, with multiple
alternatives.
Search WWH ::
Custom Search