Sunday, May 26, 2019

Difference Between For loop and for each loop in java with examples

In this post i am sharing what is for loop and for each loop and difference between them with examples.

In any programming language, loops are used to execute block of statements until the condition becomes false.For-each is another array traversing technique like for loop, while loop, do-while loop introduced in Java5.


  1. It starts with the keyword for like a normal for-loop.
  2. Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.
  3. In the loop body, you can use the loop variable you created rather than using an indexed array element.
  4. It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)

Example 1:

For each loop 

Syntax: for(data_type variable : array | collection){}

For each loop traversing the array elements:






Example 2:

For each loop traversing the Collection elements:




For loop:


The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop.


for(initialization;condition;increment/decrement){
//statement or code to be executed
}

Example:



Difference Between for loop and for each:

The for loop is present from the start i.e. JDK 1, but enhanced for loop was added on Java 5, hence it's only available from JDK 5 onward.


The enhanced for loop executes in sequence. i.e  the counter is always increased by one, where as in for loop you can change the step as per your wish e.g doing something like i=i+2; to loop every second element in an array or collection.


The enhanced for loop can only iterate in incremental order. we cannot configure it to go in decrements. i.e in for loop we can write i-- in step counter to go backward.

If we have a requirement that array should be displayed sequence in the forward direction and we also don't want to change the real value in the array accidentally or intentionally by any user etc then we should use the enhanced for loop.


let me put short answer:

 If you only want to iterate over elements from an array or a collection e.g. a list or a set then use enhanced for loop, it's convenient and less error prone, but if you want more control over iteration process then use traditional for loop. 

No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...