An if statement lets a method run an action only when a condition is true. A condition is a Boolean expression: it evaluates to either true or false. For example, an airline application can check whether a flight still has seats:
if (availableSeats > 0)
{
MessageBox.Show("Seats are available.");
}When availableSeats is 4, the message appears. When it is 0, the program skips the braces and continues after the if statement. A single if has no action reserved for the false result.
If the application needs to display one of two messages, add else:
if (availableSeats > 0)
{
MessageBox.Show("Seats are available.");
}
else
{
MessageBox.Show("This flight is full.");
}For one evaluation of the condition, exactly one branch runs. The else branch has no separate condition: it runs when the if condition is false. Execution then continues after the entire statement.
availableSeats |
availableSeats > 0 |
Message shown |
|---|---|---|
| 4 | true |
Seats are available. |
| 0 | false |
This flight is full. |
A Zoo wallet can use a condition to decide whether it has enough money for a requested payment:
if (this.MoneyBalance >= requestedAmount)
{
amountRemoved = requestedAmount;
}
else
{
amountRemoved = this.MoneyBalance;
}The first branch selects the full request; the second selects the balance that remains. This example assumes requestedAmount is not negative. A complete payment method must also decide how to handle invalid requests before changing the balance.
When reading conditional code, identify the current values, evaluate the expression in parentheses, then follow only the matching branch. Finally, look below the closing brace for the next statement. Do not assume both branches run because both appear in the source.
The next activity shows the same choice as two paths leaving a decision node in an activity diagram.