Java Reference
In-Depth Information
Figure 5-1.
Execution of an if-else statement
Suppose you have three
int
variables,
num1
,
num2
, and
num3
. You want to add
10
to
num2
and
num3
if
num1
is
greater than
50
. Otherwise, you want to subtract
10
from
num2
and
num3
. You may try the following snippet of code,
which is incorrect:
if (num1 > 50)
num2 = num2 + 10;
num3 = num3 + 10;
else
num2 = num2 - 10;
num3 = num3 - 10;
The snippet of code will generate a compiler error. What is wrong with this code? You can place only one
statement between
if
and
else
in an
if-else
statement. This is the reason that the statement
num3 = num3 + 10;
caused a compile-time error. In fact, you can always associate only one statement with the
if
part in an
if-else
statement or in a simple
if
statement. This is also true for the
else
part. In the above piece of code, only
num2 =
num2 - 10;
is associated with the
else
part; the last statement,
num3 = num3 - 10;
, is not associated with the
else
part. You want to execute two statements when
num1
is greater than
50
or not. In this case, you need to bundle two
statements into one block statement, like so:
if (num1 > 50) {
num2 = num2 + 10;
num3 = num3 + 10;
}
else {
num2 = num2 - 10;
num3 = num3 - 10;
}