Java Reference
In-Depth Information
Thisexampleassumesthat
direction
storesanintegervalue.Ifthisvalueisinthe
range0-3,anappropriatedirectionmessageisoutput;otherwise,amessageaboutbeing
lost is output.
Note
Thisexamplehardcodesvalues0,1,2,and3,whichisnotagoodideainprac-
tice. Instead, constants should be used.
Chapter 2
introduces you to constants.
Loop Statements
It's often necessary to repeatedly execute a statement, and this repeated execution is
called a
loop
. Java provides three kinds of loop statements: for, while, and do-while.
Thissectionfirstdiscussesthesestatements.Itthenexaminesthetopicofloopingover
the empty statement. Finally, the section discusses the break, labeled break, continue,
and labeled continue statements for prematurely ending all or part of a loop.
For Statement
Theforstatementletsyouloopoverastatementaspecificnumberoftimes,orevenin-
definitely. This statement has the following syntax:
for ([
initialize
]; [
test
]; [
update
])
statement
Forconsistsofreservedword
for
,followedbyaheaderinparentheses,followedby
a statement to execute. The header consists of an optional
initialize
section, fol-
lowedbyanoptional
test
section,followedbyanoptional
update
section.Anon-
optional semicolon separates each of the first two sections from the next section.
The
initialize
sectionconsistsofacomma-separatedlistofvariabledeclarations
orvariableassignments.Someorallofthesevariablesaretypicallyusedtocontrolthe
loop's duration, and are known as
loop-control variables
.
The
test
sectionconsistsofaBooleanexpressionthatdetermineshowlongtheloop
executes. Execution continues as long as this expression evaluates to true.
Finally, the
update
section consists of a comma-separated list of expressions that
typically modify the loop-control variables.
Forisperfectfor
iterating
(looping)overanarray.Each
iteration
(loopexecution)ac-
cessesoneofthearray'selementsviaan
array
[
index
]
expression,where
array
is
thearraywhoseelementisbeingaccessed,and
index
isthezero-basedlocationofthe
element being accessed.
Thefollowingexampleusestheforstatementtoiterateoverthearrayofcommand-
line arguments that is passed to the
main()
method: