Java Reference
In-Depth Information
EXAMPLE:
(continued)
The program uses a multiway
if-else
statement with one action for each of the
above three cases. The condition for the second case is actually more complicated
than it needs to be. The computer will not get to the second condition unless it
has already tried the first condition and found it to be
false
. Thus, you know that
whenever the computer tries the second condition, it knows that
netIncome
is
greater than
15000
. Hence, you can replace the line
else if
((netIncome > 15000) && (netIncome <= 30000))
with the following, and the program will perform exactly the same:
else if
(netIncome <= 30000)
Self-Test Exercises
5. What output will be produced by the following code?
int
extra = 2;
if
(extra < 0)
System.out.println("small");
else if
(extra == 0)
System.out.println("medium");
else
System.out.println("large");
6. What would be the output in Exercise 5 if the assignment were changed to the
following?
int
extra = -37;
7. What would be the output in Exercise 5 if the assignment were changed to the
following?
int
extra = 0;
8. Write a multiway
if-else
statement that classifi es the value of an
int
variable
n
into one of the following categories and writes out an appropriate message:
n < 0 or 0 ≤ n < 100 or n ≥ 100
Hint: Remember that the Boolean expressions are checked in order.