Java Reference
In-Depth Information
comment consists of everything from the opening
/*
to the closing
*/
sequence.
3.2.3.1
An experienced programmer probably only needs to see examples of
if
and
other such statements to learn them. It's only a matter of syntax. Java breaks
no new ground here; it adds no new semantics to conditional execution
constructs.
Conditional Execution
The
if-else
statement.
The
if
can take a single statement without any
braces, but we always use the braces as a matter of good style (Example 3.7).
Example 3.7
A compound Java
if-else
statement
if (x < 0) {
y = z + progo;
} else if (x > 5) {
y = z + hmron;
mylon.grebzob();
} else {
y = z + engrom;
mylon.kuggle();
}
TIP
An important thing to remember about the Java
if
statement (and all other
conditional tests, such as
while
,
do-while
, and
for
) is that, unlike C/C++,
its expression needs to evaluate to a
boolean
. In C/C++, numeric expressions
are valid, any nonzero value being considered
true
, but not so in Java.
The
switch
statement.
For a multiway branch Java, like C/C++, has a
switch
statement, though the Java version of
switch
is a bit more restrictive.
Example 3.8 shows the syntax.
In Java, the expression in the
switch
statement must evaluate to either
an
int
or a
char
. Even
short
and
long
are not allowed.
As in C/C++, be sure to put the
break
statement at the end of each
case
,
or else control will flow right into the next
case
. Sometimes this is the desired
behavior—but if you ever do that deliberately, be sure to add a comment.