Java Reference
In-Depth Information
This example is similar to its predecessor. Because the compound statement is no
longerexecutedpriortothetest,it'snolongernecessarytoinitialize ch - ch isassigned 's return value prior to the Boolean expression's evaluation.
Looping Over the Empty Statement
Java refers to a semicolon character appearing by itself as the empty statement . It's
sometimes convenient for a loop statement to execute the empty statement repeatedly.
The actual work performed by the loop statement takes place in the statement header.
Consider the following example:
for (String line; (line = readLine()) != null; Sys-
arereadfromsomesource,viathefictitious readLine() methodinthisexample,to
somedestination,via System.out.println() inthisexample.Copyingcontinues
until readLine() returnsnull.Notethesemicolon(emptystatement)attheendofthe
Caution Becarefulwiththeemptystatement becauseitcanintroducesubtlebugs
intoyourcode.Forexample,thefollowingloopissupposedtooutputthestring Hello
statement and not System.out.println() that's executed ten times:
for (int i = 0; i < 10; i++); // this ; represents the
empty statement
Break and Labeled Break Statements
What do for(;;); , while(true); and do;while(true); have in common?
Each of these loop statements presents an extreme example of an infinite loop
(a loop that never ends). An infinite loop is something that you should avoid because
point of view of your application's users.
Caution An infinite loop can also arise from a loop header's Boolean expression
example,thefollowingcodefragmentneverendsbecause 0.1 doesnothaveanexact
internal representation:
Search WWH ::

Custom Search