Java Reference
In-Depth Information
Continue and Labeled Continue Statements
Thecontinuestatementskipstheremainderofthecurrentloopiteration,re-evaluatesthe
header's Boolean expression, and performs another iteration (if true) or terminates the
loop(iffalse).Continueconsistsofreservedword continue followedbyasemicolon.
Considerawhileloopthatreadslinesfromasourceandprocessesnonblanklinesin
somemanner.Becauseitshouldnotprocessblanklines,whileskipsthecurrentiteration
when a blank line is detected, as demonstrated in the following example:
String line;
while ((line = readLine()) != null)
{
if (isBlank(line))
continue;
processLine(line);
}
Thisexampleemploysafictitious isBlank() methodtodeterminewhetherthecur-
rentlyreadlineisblank.Ifthismethodreturnstrue,ifexecutesthecontinuestatement
to skip the rest of the current iteration and read the next line whenever a blank line is
detected. Otherwise, the fictitious processLine() method is called to process the
line's contents.
Lookcarefullyatthisexampleandyoushouldrealize thatthecontinuestatement is
notneeded.Instead,thislistingcanbeshortenedvia refactoring (rewritingsourcecode
toimproveitsreadability,organization,orreusability),asdemonstratedinthefollowing
example:
String line;
while ((line = readLine()) != null)
{
if (!isBlank(line))
processLine(line);
}
Thisexample'srefactoringmodifiesif'sBooleanexpressiontousethelogicalcom-
plementoperator( ! ).Whenever isBlank() returnsfalse,thisoperatorflipsthisvalue
totrueandifexecutes processLine() .Althoughcontinueisn'tnecessaryinthisex-
ample, you'll find it convenient to use this statement in more complex code where re-
factoring isn't as easy to perform.
Thelabeledcontinuestatementskipstheremainingiterationsofoneormorenested
loopsandtransfersexecutiontothelabeledloop.Itconsistsofreservedword contin-
Search WWH ::




Custom Search