Java Reference
In-Depth Information
The curly brackets of an if statement are not required if you only have one
statement that follows the if. For example, in the preceding IfDemo program,
the following if statement does not need the curly brackets since there is only
one statement that follows: grade = C.
if(y >= 70 && y < 85)
grade = 'C';
In the if statement comparing (y >= 85), the curly brackets appear, but are
not necessary.
Try to use curly brackets all the time, even if they are not required.
They make code easier to read and modify.
The if/else Statement
An if statement can be followed by an optional else statement, which executes
when the Boolean expression is false. The syntax for an if/else looks similar to:
if( Boolean_expression )
{
//Executes when the Boolean expression is true
}
else
{
//Executes when the Boolean expression is false
}
With an if/else statement, you are guaranteed that either the if block or the
else block will execute, depending on the value of the Boolean expression.
An else can only follow a corresponding if. It does not make sense
(nor is it valid) to have a standalone else statement.
The else block can also contain another if statement, creating a series of
if/else statements in which only one if block of code will execute. The syntax
looks similar to:
if( Boolean_expression )
{
}
else if( Boolean_expression )
Search WWH ::




Custom Search