Iteration in Java Programming


Java allows you to use iteration to repeat instructions.

While Loops

A while loop is a loop that tells the program when to stop reiterating instructions. While the included condition evaluates to true, the loop continues. It is designed in the format below.

while(/*condition*/)
{
/*body*/;
}

For Loops

If the number of times a loop will be executed is always known and constant in a program, we can use a for loop to execute the loop that specific number of times. A for loop has three important parts that are displayed in parenthesis, separated by semicolons, after the keyword for.

  • loop initialization code (statement expression with a corresponding statement that begins when the for loop begins): int i = 1

  • loop condition (boolean expression that tells the loop to continue as long as it evaluates to true): i <= 10

  • loop update code (statement expression with a corresponding statement that begins when the for loop ends after each execution): i++

for loops are written in the format below.

for(/*initialization*/ ; /*condition*/ ; /*update*/)
/*body*/

For-Each Loops (with reference to arrays)

for-each loops are a shortcut for iterating through every entry within an array. They are written in the format below.

for(/*declaration*/ : /*expression*/)
/*body*/

The declaration in a for-each loop declares the variable a type and name. The expression is the name of the array of values that are used.

for-each loops make shorter, more readable code and allow errors to be found faster. Because of this, they should be used whenever possible. The situations that do not allow for-each loops to be used are as follows:

  • When iterating over an array.

  • When the index will be used for a purpose other than as an element reference.

  • When a specific order or selection of elements is required.

  • When values are assigned to elements of a collection.