Loops - StarShipTutor/StarshipTutorAPCS GitHub Wiki

There are three looping structures in Java. These loops print out the chars 0 to 9.

The For Loop

for ( int i = 0; i < 10; i++ )
{
   System.out.println(i);
}

The While Loop

int i = 0;
while (i < 10)
{
   System.out.println(i);
   i++;
}

The Do Loop

int i = 0;
do
{
   System.out.println(i);
   i++;
} while (i < 10)

The For Each Loop

Each element in the list object ( arrayOfPrimes[] in this case ) is placed in the bucket at the top of the loop and the loop is executed. All list objects have an iterator method that allows the loop to start at the top and access each element one at a time.


// This loop prints each element in arrayOfPrimes[]

int[] arrayOfPrimes = new int[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };

for ( int bucket : arrayOfPrimes )
{
     System.out.println ( bucket );

}