Mark Danishevsky

Tutorials: Iteration

Back to tutorials home

Boolean Expressions Navigation

For loop

What Is Iteration?

Iteration means repeating a set of instructions multiple times. In Java, loops allow us to automate repetitive tasks instead of writing many segments of similar code over and over.

Types of Loops in Java:

The for loop

The syntax for a for loop is as follows:

Examples of updates:

We can use a for loop to count from 1 to 5:

Traversing an array using a for loop:

Enhanced for Loop (for-each)

This is a simplified version of the for loop used to iterate over arrays. It is appreciated for its simpler and more elegant syntax.

Note: In for-each loops, the variable corresponds to a value, not an index.

Example of a for-each loop:

The loop automatically:

Use for-each loops when:

While Loop

Unlike for loops, which are best when you know how many times to repeat, while and do-while loops are useful when the number of repetitions is unknown.

What happens in the loop:

Example of input validation using a while loop:

do-while Loop

What it does:

Example of a simple menu system with a do-while loop: