Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

5 Control Statements


5 Control Statements


A


programming language usescontrolstatements to cause the flow of execution to
advance and branch based on changes to the state of a program. Java’s program
control statements can be put into the following categories: selection, iteration, and
jump.Selectionstatements allow your program to choose different paths of execution based
upon the outcome of an expression or the state of a variable.Iterationstatements enable
program execution to repeat one or more statements (that is, iteration statements form
loops).Jumpstatements allow your program to execute in a nonlinear fashion. All of Java’s
control statements are examined here.

Java’s Selection Statements


Java supports two selection statements:ifandswitch. These statements allow you to control the
flow of your program’s execution based upon conditions known only during run time. You will
be pleasantly surprised by the power and flexibility contained in these two statements.

if


Theifstatement was introduced in Chapter 2. It is examined in detail here. Theifstatement
is Java’s conditional branch statement. It can be used to route program execution through
two different paths. Here is the general form of theifstatement:

if (condition)statement1;
elsestatement2;

Here, eachstatementmay be a single statement or a compound statement enclosed in curly
braces (that is, ablock). Theconditionis any expression that returns abooleanvalue. Theelse
clause is optional.
Theifworks like this: If theconditionis true, thenstatement1is executed. Otherwise,
statement2(if it exists) is executed. In no case will both statements be executed. For example,
consider the following:

int a, b;
// ...
if(a < b) a = 0;
else b = 0;

77

Free download pdf