Simple for loop and enhanced for loop in Java

This post provides an overview of for loop in Java which is used to repeatedly execute a set of instructions until a specified condition is satisfied.


 

There are two types of for-loops in Java: Simple for loop and enhanced for loop (for-each loop). Let’s explore each one of them in detail –

 

1. Simple for loop

We can use simple 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. Then 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.

To illustrate the working of a simple for loop, consider below program which prints the numbers 0 through 9.

 

Download   Run Code

 
Please 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 for loop which is even more compact and more readable than simple for loop. It is called enhanced for loop (or for-each loop) and used to iterate through Collections and arrays. It is available to any object implementing Iterable Interface and invokes the iterator() method behind the scenes.

Consider the following program which uses the enhanced for loop to iterate through the array:

 

Download   Run Code

The output of above program is:

1
2
3
4
5

 
Also Read: While loop and do-while loop in Java

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of