Java Reference
In-Depth Information
Using
if
, you can include only a single statement as the code to execute if the test
expression is true and another statement if the expression is false.
However, as you learned earlier today, a block can appear anywhere in Java that a single
statement can appear. If you want to do more than one thing as a result of an
if
state-
ment, you can enclose those statements inside a block. Note the following snippet of
code, which was used on Day 1, “Getting Started with Java”:
if (temperature > 660) {
status = “returning home”;
speed = 5;
}
The
if
statement in this example contains the test expression
temperature > 660
. If the
temperature
variable contains a value higher than 660, the block statement is executed,
and two things occur:
The
status
variable is given the value
returning home
.
n
The
speed
variable is set to
5
.
n
If the
temperature
variable is equal to or less than 660, the entire block is skipped, so
nothing happens.
All
if
and
else
statements use Boolean tests to determine whether statements are exe-
cuted. You can use a
boolean
variable itself for this test, as in the following:
if (outOfGas)
status = “inactive”;
The preceding example uses a
boolean
variable called
outOfGas
. It functions exactly like
the following:
if (outOfGas == true)
status = “inactive”;
A common programming practice is to test a variable against a value, and if it doesn't
match, test it again against a different value, and so on.
This approach can become unwieldy if you're using only
if
statements, depending on
how many different values you have to test. For example, you might end up with a set of
if
statements something like the following:
if (operation == '+')
add(object1, object2);