Java Reference
In-Depth Information
You'll use the simple
if
statement when you have code that you want to execute
sometimes and skip other times. Java also has a variation known as the
if/else
statement that allows you to choose between two alternatives. Suppose, for example,
that you want to set a variable called
answer
to the square root of a number:
answer = Math.sqrt(number);
You don't want to ask for the square root if the number is negative. To avoid this
potential problem, you could use a simple
if
statement:
if (number >= 0) {
answer = Math.sqrt(number);
}
This code will avoid asking for the square root of a negative number, but what
value will it assign to
answer
if
number
is negative? In this case, you'll probably
want to give a value to
answer
either way. Suppose you want
answer
to be
-1
when
number
is negative. You can express this pair of alternatives with the following
if/else
statement:
if (number >= 0) {
answer = Math.sqrt(number);
} else {
answer = -1;
}
The
if/else
statement provides two alternatives and executes one or the other.
So, in the code above, you know that
answer
will be assigned a value regardless of
whether
number
is positive or negative.
The general form of the
if/else
statement is:
if (<test>) {
<statement>;
<statement>;
...
<statement>;
} else {
<statement>;
...
<statement>;
<statement>;
}
Search WWH ::
Custom Search