Java Reference
In-Depth Information
This explanation should make it clear that the
for
loop in Example 1-2 counts
from 1 to 100.
The
if/else
statement is simpler than the
for
statement. Its syntax is:
if (
expression
)
statement1
else
statement2
When Java encounters an
if
statement, it evaluates the specified
expression
.If
the expression evaluates to
true
,
statement1
is executed. Otherwise,
statement2
is evaluated. That is all
if/else
does; there is no looping involved, so the program
continues with the next statement following
if/else
. The
else
clause and
state-
ment2
that follows it are entirely optional. If they are omitted, and the
expression
evaluates to
false
, the
if
statement does nothing. The statements following the
if
and
else
clauses can either be single Java statements or entire blocks of Java code,
contained within curly braces.
The thing to note about the
if/else
statement (and the
for
statement, for that
matter) is that it can contain other statements, including other
if/else
statements.
This is how the statement was used in Example 1-2, where we saw what looked
like an
if/elseif/elseif/else
statement. In fact, this is simply an
if/else
state-
ment within an
if/else
statement within an
if/else
statement. This structure
becomes clearer if the code is rewritten to use curly braces:
if (((i % 5) == 0)&& ((i % 7) == 0))
System.out.print("fizzbuzz");
else {
if ((i % 5) == 0)
System.out.print("fizz");
else {
if ((i % 7) == 0)
System.out.print("buzz");
else
System.out.print(i);
}
}
Note, however, that this sort of nested
if/else
logic is not typically written out
with a full set of curly braces in this way. The
else if
programming construct is a
commonly used idiom that you will quickly become accustomed to. You may have
also noticed that I use a compact coding style that keeps everything on a single
line wherever possible. Thus, you'll often see:
if (
expression
)
statement
I do this so that the code remains compact and manageable, and therefore easier
to study in the printed form in which it appears here. You may prefer to use a
more highly structured, less compact style in your own code.