Java Reference
In-Depth Information
canappearwhereversimplestatementsappearandarealternativelyreferredto
as
blocks
.
Thissection introduces youtomanyofJava'sstatements. Additional statements are
covered in later chapters. For example,
Chapter 2
discusses the return statement.
Assignment Statements
The
assignment statement
isanexpressionthatassignsavaluetoavariable.Thisstate-
mentbeginswithavariablename,continueswiththeassignmentoperator(
=
)oracom-
poundassignmentoperator(suchas
+=
),andconcludeswithanexpressionandasemi-
colon. Below are three examples:
x = 10;
ages[0] = 25;
counter += 10;
The first example assigns integer
10
to variable
x
, which is presumably of type in-
tegeraswell.Thesecondexampleassignsinteger
25
tothefirstelementofthe
ages
array.Thethirdexampleadds
10
tothevaluestoredin
counter
andstoresthesumin
counter
.
Note
Initializing a variable in the variable's declaration (e.g.,
int counter =
1;
) can be thought of as a special form of the assignment statement.
Decision Statements
Thepreviouslydescribedconditionaloperator(
?:
)isusefulforchoosingbetweentwo
expressionstoevaluate,andcannotbeusedtochoosebetweentwostatements.Forthis
purpose, Java supplies three decision statements: if, if-else, and switch.
If Statement
The if statement evaluates a Boolean expression and executes another statement when
this expression evaluates to true. This statement has the following syntax:
if (
Boolean expression
)
statement
Ifconsistsofreservedword
if
,followedbya
Boolean expression
inparen-
theses,followedbya
statement
toexecutewhen
Boolean expression
evalu-
ates to true.
The following example demonstrates this statement: