for loop : Java Glossary

go to home page F words local find full screen, hide local find menu Google search web for more information on this topic jump to foot of page translate this page with Babelfish punctuation 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z (all) ©1996-2009 Roedy Green, Canadian Mind Products
for loop
The for is Java’s multipurpose loop controller. It is most commonly used in this form:
for ( int i=0; i<n; i++ )
   {
   System.out.println(i);
   }
You can leave out any of the three sections of the
for ( init; should-I-continue-looping?; increment )
sections. If you leave out the should-I-continue-looping? boolean expression, it is assumed true. This means you can use a for to simulate while and do whileloops.

The other common use of for is to iterate over a collection like this:

for ( Iterator aIter = myCollection.iterator(); aIter.hasNext(); )
   {
   Thing item = (Thing) aIter.next();
   // do something with item
   }
Note the empty increment portion of the for. You have to do the next inside the loop body for iterators. for is preferable to using a while loop because the aIter variable is automatically made local to the loop.

For loops can have a dual index, like this:

for ( int i=0, j=n; i<n; i++,j-- )
   {
   /* loop body */
   }
or like this:
{
   int i,j;
   for ( i=0,j=n; i<n; i++,j-- )
      {
      /* loop body */
      }
}
or like this:
{
   int i;
   float f;
   for ( i=0,f=n; i<n; i++,f*=.5 )
      {
      /* loop body */
      }
}
But, due to a hopelessly muddled for syntax dating back to C, (deriving from the attempt to reuse comma and semicolon in incompatible ways) you cannot write code like this:
for ( int i=0, float f=n; i<n; i++,f*=.5 )
   {
   /* loop body */
   }
For loops allow two kinds of controlled goto, the break and the continue. break leaps out of the loop entirely. continue jumps to the end of the loop and continues looping. By labelling your for loops with words like inner: and outer: you can break out of two or more levels of nesting with break outer; or continue outer;. break and continue work with while, do while and switch statements as well.


CMP homejump to top You can get the freshest copy of this page from: or possibly from your local J: drive (Java virtual drive/mindprod.com website mirror)
http://mindprod.com/jgloss/forloop.html J:\mindprod\jgloss\forloop.html
CMP logofeedback Please email your feedback for publication, errors, omissions, typos, formatting errors, ambiguities, unclear wording, broken/redirected link reports, suggestions to improve this page or comments to Roedy Green : feedback email
mindprod.com IP:[65.110.21.43]
view BlogYour face IP:[38.107.191.109]
You are visitor number 170,259.