Java Reference
In-Depth Information
Compound Statements
You will often want the branches of an if-else statement to execute more than one
statement each. To accomplish this, enclose the statements for each branch between
a pair of braces, { and }. A list of statements enclosed in a pair of braces is called a
compound statement . 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
Statement Alternatives” version described in the box entitled “ if-else Statement” is
really just a special case of the “simple” case with one statement in each branch.
if-else
with multiple
statements
compound
statement
if-else Statement
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 )
Yes_Statement
else
No_Statement
Be sure to note that the
Boolean_Expression must be
enclosed in parentheses.
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
happens and the program goes on to the next statement.
EXAMPLE
if (weight > ideal)
calorieAllotment = calorieAllotment - 500;
 
Search WWH ::




Custom Search