Java Reference
In-Depth Information
// A compile-time error. num2 is local to the inner block.
// So, it cannot be used outside the inner block.
num2 = 200;
}
// End of the outer block
One important thing to remember about nested block statement is that you cannot define a variable with the
same name inside an inner block if a variable with the same name has already been defined in the outer block. This
is because the variables declared in the outer block can always be used inside the inner block and if you declare
a variable with the same name inside the inner block, there is no way for Java to differentiate between these two
variables inside the inner block. The following snippet of code is incorrect:
int num1 = 10;
{
// A compile-time error. num1 is already in scope. Cannot redeclare num1
float num1 = 10.5F;
float num2 = 12.98F; // OK
{
// A compile-time error. num2 is already in scope. You can use
// num2 already define in the outer block, but cannot redeclare it.
float num2;
}
}
The if-else Statement
The format of an
if-else
statement is
if (condition)
statement1
else
statement2
The
condition
must be a
Boolean
expression. That is, it must evaluate to
true
or
false
. If the
condition
evaluates to
true
,
statement1
is executed. Otherwise,
statement2
is executed. The
else
part is optional. You may
write a statement as
if (condition)
statement1
Suppose there are two
int
variables,
num1
and
num2
. You want to add
10
to
num2
if
num1
is greater than
50
.
Otherwise, you want to subtract
10
from
num2
. You can write this logic using an
if-else
statement.
if (num1 > 50)
num2 = num2 + 10;
else
num2 = num2 - 10;
The execution of this
if-else
statement is shown in Figure
5-1
.