Java Glossary : for loop

CMP home Java glossary home Menu no menu Last updated 2004-06-28 by Roedy Green ©1996-2004 Canadian Mind Products

Java definitions: 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

You are here : home : Java Glossary : F words : for loop.

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 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 logo
CMP_home
home
Canadian Mind Products CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[24.87.56.253]
Your IP:[80.134.30.163]
You are visitor number 6570.
Please send errors, omissions and suggestions
to improve this page to Roedy Green.
You can get a fresh copy of this page from: or possibly from your local J: drive mirror:
http://mindprod.com/jgloss/forloop.html J:\mindprod\jgloss\forloop.html