Java Reference
In-Depth Information
The assignment statement is carried out only when the amount to be withdrawn is less
than or equal to the balance (see
Figure 1
).
Let us make the
withdraw
method of the
BankAccount
class even more realistic.
Most banks not only disallow withdrawals that exceed your account balance; they
also charge you a penalty for every attempt to do so.
This operation can't be programmed simply by providing two complementary
if
statements, such as:
if (amount <= balance)
balance = balance - amount;
if (amount > balance) // NO
balance = balance - OVERDRAFT_PENALTY;
There are two problems with this approach. First, if you need to modify the condition
amount = balance
for some reason, you must remember to update the condition
amount > balance
as well. If you do not, the logic of the program will no longer
be correct. More importantly, if you modify the value of
balance
in the body of the
first
if
statement (as in this example), then the second condition uses the new value.
To implement a choice between alternatives, use the
if/else
statement:
if (amount <= balance)
balance = balance - amount;
else
balance = balance - OVERDRAFT_PENALTY;
Now there is only one condition. If it is satisfied, the first statement is executed.
Otherwise, the second is executed. The flowchart in
Figure 2
gives a graphical
representation of the branching behavior.
183
184
Quite often, however, the body of the
if
statement consists of multiple statements
that must be executed in sequence whenever the condition is true. These statements
must be grouped together to form a block statement by enclosing them in braces
{ }
.
Here is an example.
A block statement groups several statements together.
if (amount <= balance)