This post provides an overview of for loop and enhanced for loop (for-each loop) in Java.

A loop is used to repeatedly execute a set of instructions until a specified condition is satisfied. There are several types of loops in Java: for loop, enhanced for loop (for-each loop), while loop and do-while loop. This post will explore for loop and enhanced for loop in detail:

1. For loop

A for loop is a type of loop that executes a block of code a specified number of times. We can use a for loop in Java to iterate over a range of values. The syntax of the for loop is:

 
Here, the initialization expression is executed once before the first iteration of the loop. It is used to initialize the counter for the loop. After every iteration of the loop, the counter gets incremented or decremented based on the expression, and the termination condition is evaluated. The loop terminates when the termination condition evaluates to false; otherwise, the loop body is executed. The increment/decrement expression can be either an increment operator (++) or a decrement operator (--), or any other assignment statement. To illustrate the working of a for loop, consider the following program, which outputs the integers from 0 to 10.

Download  Run Code

 
In this example, the variable i is initialized to 0, and the condition is i < 10. The loop will run as long as i is less than 10. After each iteration, i is incremented by 1 using the i++ expression. Note that the initialization, termination, and increment/decrement steps are optional. Skipping all three expressions results in an infinite loop:

2. Enhanced for loop (for-each loop)

There is another variation of the regular for loop, which is even more compact and more readable. It is called an enhanced for loop, and it simplifies the iteration over arrays and collections. It is also known as the for-each loop because it traverses each element one by one. It is available to any object implementing the Iterable interface and invokes the iterator() method behind the scenes. The syntax of the enhanced for loop is:

 
The type is the data type of the array or collection elements. The e is a variable that stores the current element in each iteration. The iterable is the name of the array or collection that we want to loop through. The following program uses the enhanced for loop to print all the elements of an array:

Download  Run Code

 
The advantage of the enhanced for loop is that it makes the code more readable and eliminates the possibility of programming errors. It also avoids the use of index variables and counters that are often used in regular for loops. The drawback of the enhanced for loop is that it cannot traverse the elements in reverse order, skip any element, or modify the original array or collection.

That's all about for loop and enhanced for loop (for-each loop) in Java.