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 by Roedy Green ©1996-2009 Canadian Mind Products
index page for letter ⇒ 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)
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
CMP logo
feedback Please email your feedback for publication, errors, omissions, broken/redirected link reports
and suggestions to improve this page to Roedy Green : feedback email
made with CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[65.110.21.43]
Your face IP:[38.103.63.62] Spread the Net
You are visitor number 138,197.
You can get a fresh 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