Java Reference
In-Depth Information
The two forms are identical except for the spacing and indentation, which the compiler
ignores. The latter form avoids deep indentation of the code to the right. Such indentation
often leaves little room on a line of source code, forcing lines to be split.
Dangling-
else
Problem
The Java compiler always associates an
else
with the immediately preceding
if
unless told
to do otherwise by the placement of braces (
{
and
}
). This behavior can lead to what is
referred to as the
dangling-
else
problem
. For example,
if
(x >
5
)
if
(y >
5
)
System.out.println(
"x and y are > 5"
);
else
System.out.println(
"x is <= 5")
;
appears to indicate that if
x
is greater than
5
, the nested
if
statement determines whether
y
is also greater than
5
. If so, the string
"xandyare>5"
is output. Otherwise, it appears
that if
x
is not greater than
5
, the
else
part of the
if
…
else
outputs the string
"x is <= 5"
.
Beware! This nested
if
…
else
statement does
not
execute as it appears. The compiler ac-
tually interprets the statement as
if
(x >
5
)
if
(y >
5
)
System.out.println(
"x and y are > 5"
);
else
System.out.println(
"x is <= 5"
);
in which the body of the first
if
is a
nested
if
…
else
. The outer
if
statement tests whether
x
is greater than
5
. If so, execution continues by testing whether
y
is also greater than
5
. If
the second condition is
true
, the proper string—
"x
and
y
are
>
5"
—is displayed. However,
if the second condition is
false
, the string
"x
is
<=
5"
is displayed, even though we know
that
x
is greater than
5
. Equally bad, if the outer
if
statement's condition is false, the inner
if
…
else
is skipped and nothing is displayed.
To force the nested
if
…
else
statement to execute as it was originally intended, we
must write it as follows:
if
(x >
5
)
{
if
(y >
5
)
System.out.println(
"x and y are > 5")
;
}
else
System.out.println(
"x is <= 5"
);
The braces indicate that the second
if
is in the body of the first and that the
else
is
associated with the
first
if
. Exercises 4.27-4.28 investigate the dangling-
else
problem
further.
Blocks
The
if
statement normally expects only
one
statement in its body. To include
several
state-
ments in the body of an
if
(or the body of an
else
for an
if
…
else
statement), enclose
the statements in braces. Statements contained in a pair of braces (such as the body of a