| The else statement |
| |
| 1) Defines an alternative and mutually exclusive logic path to be
followed if the preceding if statement
expression evaluates to false |
| |
| 2) Must always be paired with, and follow, an
if statement. It can never be
coded separately |
| |
| 3) Have two forms. |
| |
| The general syntax is either of the following: |
else statement;
or
else
{
statements;
}
|
| |
| The first form is often referred to
as a "single
statement else". |
| |
| For example, |
if (amountDue > 0)
System.out.println("You owe " + amountDue);
else
System.out.println("You owe nothing"); |
| |
| will add to the grand total and display how much
is owed if amountDue is greater than zero. Otherwise, the customerRating will
be set to 'A' and the "You owe nothing" message will be displayed. |
| |
| The two logic paths are mutually exclusive and
merge at the first statement after the end of the else block. |
| |
| 4) Can trap programmers who get sloppy. |
| |
| For example, |
if (age < 65)
System.out.println("Regular admission");
else;
System.out.println("Senior admission"); |
| |
| will always display the "Senior admission" message no matter
what value age has. The accidental semicolon after the else says that if
the expression is false you want to do nothing. Logic then merges at the
next statement, so the message is always displayed.
|