4.3 The if Statement | 169
if (hours <= 40.0)
pay = rate hours;
else
pay = rate (40.0+ (hours – 40.0) * 1.5);
System.out.println("Pay is "+ pay);
In terms of instructions to the computer, this code fragment says, “If hoursis less than or equal
to 40.0, compute the regular pay and then go on to execute the output statement. But if hours
is greater than 40, compute the regular
pay and the overtime pay, and then go
on to execute the output statement.”
Figure 4.4 shows the flow of control of
this ifstatement.
If-elsestatements are often used to
check the validity of input. For exam-
ple, before we ask the computer to di-
vide by a data value, we should be sure
that the value is not zero. (Even com-
puters can’t divide something by zero. If
you try it with intvalues, the computer
will halt the execution of your applica-
tion. With floating-point types, you get
the special infinity value.) If the divisor
is zero, our code should display an error
message. Here’s an example that prints
an error message:
if (divisor != 0)
result = dividend / divisor;
else
System.out.println("Division by zero is not allowed.");
Before we examine ifstatements further, let’s take another look at the syntax template
for if-else. According to the template, no semicolon appears at the end of an ifstatement. In
both of the preceding code fragments—the worker’s pay and the division-by-zero exam-
ples—there seems to be a semicolon at the end of each ifstatement. In reality, the semicolons
belong to the statements in the thenclause and the elseclause in those examples; assignment
statements end in semicolons, as do method calls. The ifstatement doesn’t have its own semi-
colon at the end.
Blocks (Compound Statements)
In our division-by-zero example, suppose that when the divisor is equal to zero we want to
do twothings: write the error message andset the variable named resultequal to a special
value such as Integer.MAX_VALUE. We would need two statements in the same branch to do
so, but the syntax template seems to limit us to one.
pay = rate*hours;
System.out.println("Pay is "+ pay);
pay = rate*( 40. 0 +(hours-40.0)* 1. 5
false true
if( hours <= 40. 0 )
else
Figure 4.4 Flow of Control for Calculating Pay