Difference between for and for each loop in java

Let’s learn difference between for and for each loop in java.

Difference between for and for each loop in java

Here’s the difference between for loop and for-each loop in java.

for loopfor each loop
Here in for loop we can increase counter as per our wish.Executes in a sequential manner. Counter will increase by one.
for loop was introduced from start, JDK 1.for each loop was introduced from JDK 5 onwards.
for loop can iterate on any container object.To loop over containers using for each loop, container should implement Iterable interface.
for loop can replace elements at any specific index.can’t replace element at specific index since there is no access to index.
for loop can iterate in both increment and decrement order.we can only iterate in incremental order cannot decrement.
In for loop array elements can be printed in forward and reverse order.In for each loop array elements can be printed only in forward order not in reverse order.

Here’s the program on difference between foreach and for loop.

// One dimensional array using for loop
int[] num = {2,4,6};
for(int a = 0; a < num.length; a++)
{
   System.out.println(num[a]);
}

// One dimensional array using for-each loop
int[] num = {2,4,6};
for(int a :  num)
{
   System.out.println(a);
}

Also read – static keyword in java