Java Reference
In-Depth Information
Note
If there is only a single statement following the if condition, the
curly brackets are optional. It is recommended to use the brackets, even
when unnecessary, both to make it more clear to someone reading the
code and also to improve maintainability. For instance, if you (or another
programmer) later add additional statements to the if-then statement,
you will not risk forgetting to place brackets around the entire block at
that time.
For a concrete example of if-then statements, imagine a banking program that prints a short noti-
fication at the bottom of each ATM transaction receipt according to the remaining balance on the
account. This example prints to the console for simplicity's sake.
if (accountBalance > 100) {
System.out.println("Safe balance.");
}
If the value of the variable
accountBalance
is greater than
100
, then output a notification of "
Safe
balance."
to the console. If
accountBalance
is not greater than
100
, nothing will happen.
The basic if-then statement can also be extended with the keyword
else
. This provides an alterna-
tive set of statements to be executed if the condition is not true.
if (accountBalance > 100) {
System.out.println("Safe balance.");
} else {
System.out.println("Warning: Low balance.");
}
Now, if
accountBalance
is greater than
100
, the same notification will be printed. However, if
accountBalance
is less than or equal to
100
, a different notification will be printed.
The
else
keyword can also be followed by a second
if
statement, which is then evaluated only if
the first condition is
false
.
if (accountBalance > 100) {
System.out.println("Safe balance.");
} else if (accountBalance < 0){
System.out.println("ALERT: Negative balance!");
} else {
System.out.println("Warning: Low balance.");
}
The first
if
condition is evaluated if
accountBalance
is greater than
100
, at which point the
"Safe
balance."
notification will print and nothing further is executed. If
accountBalance
is not greater
than
100
, the second
if
condition is evaluated. If
accountBalance
is less than
0
, the
ALERT
will be
printed and nothing further will be executed. If
accountBalance
is not less than 0, that is, if
account-
Balance
is between
0
and
100
, the warning will be printed, and the end of the statement is reached.
Search WWH ::
Custom Search