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 change counter as per our wish.Executes in a sequential manner. Counter will increase by one.
was introduced from start, JDK 1.was introduced from JDK 5 onwards.
can iterate on any container object.To loop over containers using for each loop, container should implement Iterable interface.
can replace elements at any specific index.can’t replace element at specific index since there is no access to index.
can iterate in both increment and decrement order.we can only iterate in incremental order cannot decrement.

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