Java Reference
In-Depth Information
Compound Statements
if-else
with
multiple
statements
compound
statement
You will often want the branches of an
statement to execute more than one
statement each. To accomplish this, enclose the statements for each branch between a
pair of braces,
if-else
{
and
}
. A list of statements enclosed in a pair of braces is called a
com-
. A compound statement is treated as a single statement by Java and
may be used anywhere that a single statement may be used. Thus, the “Multiple State-
ment Alternatives” version described in the box entitled “
pound statement
Statement” is really
just a special case of the “simple” case with one statement in each branch.
if-else
Statement
if-else
The
if-else
statement chooses between two alternative actions based on the value of a
Boolean_Expression
; that is, an expression that is either
true
or
false
, such as
balance < 0
.
SYNTAX
if
(
Boolean_Expression
)
Be sure to note that the
Boolean_Expression
must
be enclosed in parentheses.
Yes_Statement
else
No_Statement
If
Boolean_Expression
is
true
,
then
Yes_Statement
is executed. If
Boolean_Expression
is
false
, then
No_Statement
is executed.
EXAMPLE
if
(time < limit)
System.out.println("You made it.");
else
System.out.println("You missed the deadline.");
Omitting the
else
Part
You may omit the
else
part to obtain what is often called an
if
statement
.
Syntax
if
(
Boolean_Expression
)
Action_Statement
If
Boolean_Expression
is true, then
Action_Statement
is executed; otherwise, nothing hap-
pens and the program goes on to the next statement.
EXAMPLE
if
(weight > ideal)
calorieAllotment = calorieAllotment - 500;