Java Reference
In-Depth Information
You will often find yourself writing code that you want to execute some of the time
but not all of the time. For example, if you are writing a game-playing program, you
might want to print a message each time the user achieves a new high score and store
that score. You can accomplish this by putting the required two lines of code inside
an
if
statement:
if (currentScore > maxScore) {
System.out.println("A new high score!");
maxScore = currentScore;
}
The idea is that you will sometimes want to execute the two lines of code inside the
if
statement, but not always. The test in parentheses determines whether or not the
statements inside the
if
statement are executed. In other words, the test describes
the conditions under which we want to execute the code.
The general form of the
if
statement is as follows:
if (<test>) {
<statement>;
<statement>;
...
<statement>;
}
The
if
statement, like the
for
loop, is a control structure. Notice that we once
again see a Java keyword (
if
) followed by parentheses and a set of curly braces
enclosing a series of controlled statements.
The diagram in Figure 4.1 indicates the flow of control for the simple
if
state-
ment. The computer performs the test, and if it evaluates to
true
, the computer exe-
cutes the controlled statements. If the test evaluates to
false
, the computer skips the
controlled statements.
Ye s
Is the test true?
Execute the
controlled statement(s)
No
Execute the statement
after the
if
statement
Figure 4.1
Flow of
if
statement
Search WWH ::
Custom Search