Java Reference
In-Depth Information
2.2.3 Nested conditionals
Conditional structures may also be nested yielding various complex program
workflows. For example, we may further enhance the output message of our
former date comparison as follows:
int
h1 =... , m1 =... , s1 =...;
int
h2 =... , m2 =... , s2 =...;
int
hs1 = 3600
∗
∗
h1 + 60
m1 + s 1 ;
int
hs2 = 3600
∗
h2 + 60
∗
m2 + s 2 ;
int
d=hs2
−
hs1 ;
if
(d
>
0)
{
System . out . println (
"larger"
);
}
else
{
if
(d
<
0)
{
System . out . println (
"smaller"
);
}
else
{
System . out . println (
"identical"
);
}
}
Since these branching statements are all single instruction blocks, we can also
choose to remove the braces as follows:
if (d>0) System.out.println("larger");
else
if (d<0)
System.out.println("smaller");
else
System.out.println("identical");
However, we do not recommend it as it is a main source of errors to novice
programmers. Note that in Java there is
no
shortcut
1
for
else if
. In Java, we
need to write plainly
else if
. There can be any arbitrary
level
of nested
if
else
conditional statements, as shown in the generic form below:
if
(predicate1)
{
Block1
}
else
{
if
(predicate2)
{
Block2
}
else
if
(predicate3)
{
Block3
}
else
{
...
}
}
1
In some languages such as Maple
R
, there exists a dedicated keyword like
elif
.
Search WWH ::
Custom Search